﻿using System;
using System.IO;
using System.Data;
using System.Linq;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Text.RegularExpressions;

using CE.User;
using CE.Global;
using CE.Database;
using CE.Provider;
using CE.CarInsurance;
using CE.Company;
using CE.Mail;
using CE.InputOut;
using System.Net;

public partial class car_insurance_quote_results : MyLanguageAndSessionBasePage
{
    //int _currentRow = 0;
    string _redirectUrl = "";

    protected void Page_Load(object sender, EventArgs e)
    {
        Master.Page.Title = Resources.Title.QuoteResultsTitle;

        LiteralControl newln = new LiteralControl(Environment.NewLine);
        HtmlMeta language = new HtmlMeta();
        language.Name = "language";
        language.Content = Resources.Title.PageLanguage;

        HtmlMeta keywords = new HtmlMeta();
        keywords.Name = "keywords";
        keywords.Content = Resources.Title.QuoteResultsKeyword;

        HtmlMeta description = new HtmlMeta();
        description.Name = "description";
        description.Content = Resources.Title.QuoteResultsDescription;

        Page.Header.Controls.AddAt(10, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(11, language);
        Page.Header.Controls.AddAt(12, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(13, keywords);
        Page.Header.Controls.AddAt(14, new LiteralControl(Environment.NewLine));
        Page.Header.Controls.AddAt(15, description);

        LiteralLink.Text = "";

        HtmlControl htmlctrl = (HtmlControl)Master.FindControl("divPartnersLogo");
        htmlctrl.Visible = false;
        if (Session[CE.Global.General.UserId] != null && Session[CE.Global.General.UserTypeId] != null)
        {
            if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.Customer) && Convert.ToInt32(Session[CE.Global.General.UserTypeId]) !=
                Convert.ToInt32(CE.Global.CEUserType.Provider))
            {
                Response.Redirect("sign-in.aspx");
            }
        }
        else
        {
            Response.Redirect("sign-in.aspx");
        }

        if (Session[General.CarId] == null || Session[General.CarPolicyId] == null)
        {
            string isCXLive = CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.IsCXLive").ToString();

            Response.Redirect("~/car-insurance/");
        }
        else
        {
            hplCarResults.NavigateUrl = "";
        }

        if (Session[General.IsCarRestoreResult] != null)
        {
            hplProfile.NavigateUrl = "";
            hplCarDetails.NavigateUrl = "";
        }

        if (Page.ClientScript.IsStartupScriptRegistered("addScriptShowHideAll") == false)
        {
            Page.ClientScript.RegisterStartupScript(Type.GetType("System.String"), "addScriptShowHideDriver", "ShowHideAll()", true);
        }
        if (Page.IsPostBack)
        {
            Session["IsFromAutoLogin"] = "0";
        }
        if (!Page.IsPostBack)
        {
            Session["CIMSG"] = null;
            Session["UMMSG"] = null;

            if (Request.Params["lang"] != null)
            {
                if (Request.Params["lang"].ToString() != "th-TH")
                {
                    litZopim.Visible = true;
                    divTopLeft.Attributes.Add("class", "leftcolTop");
                }
                else
                {
                    litZopim.Visible = false;
                    divTopLeft.Attributes.Add("class", "leftcolTopTh");
                }
            }

            Session[CE.Global.General.CarResultId] = null;
            if (Session[General.UserId] != null && !CheckViewCount())
            {
                divMessage.Visible = true;
                lblMessage.Visible = true;
                lblMessage.Text = "<br />Due to speed optimization reasons, each user is restricted to 5 quotes per day.<br />Please visit us tomorrow.";
                return;
            }
            else
            {
                divMessage.Visible = false;
                lblMessage.Visible = false;
                int resultCalculatePremium = 0;                
                if ((Session["IsFromAutoLogin"] == null) || (Session["IsFromAutoLogin"] != null && Session["IsFromAutoLogin"].ToString() != "1"))
                    resultCalculatePremium = CalculatePremium();
                #region Edit Change Class
                if (Session["FROMCARDETAIL"] != null && Session["FROMCARDETAIL"].ToString() == "1")
                {
                    if (resultCalculatePremium == 0)
                    {
                        CarPolicy _carpolicy = new CarPolicy();
                        CarPolicyDB _carpolicydb = new CarPolicyDB();
                        if (Session[General.CarPolicyId] != null)
                        {
                            //CAR POLICY DETAILS
                            //Change to 2+
                            Int64 _refceuserid = 0;
                            Int64 _carid = 0;

                            if (Session[General.UserId] != null)
                            {
                                _refceuserid = Convert.ToInt64(Session[General.UserId].ToString());
                            }

                            if (Session[General.CarId] != null)
                            {
                                _carid = Convert.ToInt64(Session[General.CarId].ToString());
                            }

                            _carpolicy = _carpolicydb.GetCarPolicy(_carid, _refceuserid);
                            if (_carpolicy != null)
                            {
                                _carpolicy.InsuranceType = 21;
                                if (_carpolicy.Deductible == -1 || _carpolicy.Deductible == 5000)
                                {
                                    _carpolicy.Deductible = 0;
                                }
                                _carpolicy.IsCTPL = false;
                                _carpolicy.IsAddDriver = false;
                                _carpolicy.NoOfDriver = 0;

                                CarDriverDB _cardriverdb = new CarDriverDB();
                                _cardriverdb.UpdateAllStatus(_carid, _refceuserid);
                                _cardriverdb = null;
                                Int64 _policyresult = 0;
                                _policyresult = _carpolicydb.Insert(_carpolicy);

                                resultCalculatePremium = CalculatePremium();
                            }
                        }
                        _carpolicy = null;
                        _carpolicydb = null;
                    }
                    Session["FROMCARDETAIL"] = null;
                }

                #endregion

                ShowQuoteSummary();
                #region GetSearch
                LoadManufactYearList();
                ClearAllList();

                if (Session[General.CarPolicyId] != null && Session[General.CarId] != null)
                {
                    Int64 _cecarid = Convert.ToInt64(Session[General.CarId]);
                    Int64 _cepolicyid = Convert.ToInt64(Session[General.CarPolicyId]);
                    ShowCarAndPolicyDetail(_cecarid, _cepolicyid, 0);
                    DriverSetting();
                    OtherValidation();
                }
                else
                {
                    DriverSetting();
                }

                Int64 _userId = 0;
                if (Session[General.UserId] == null && Session[General.CarId] != null && Session[CE.Global.General.UserProfileAndContactComplete] != null)
                {
                    ShowCustomerDetailByCar(Convert.ToInt64(Session[General.CarId].ToString()));
                }
                else if (Session[General.UserId] != null)
                {
                    checkIsAgreement.Visible = false;

                    _userId = Convert.ToInt64(Session[General.UserId].ToString());
                    if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                        Convert.ToInt32(CE.Global.CEUserType.Customer))
                    {
                        ShowCustomerDetail(_userId);
                    }
                    else if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                        Convert.ToInt32(CE.Global.CEUserType.Provider))
                    {
                        ShowCustomerDetail(_userId);
                    }
                }

                if (rdoYesClaimLastYear.Checked || rdoNoClaimLastYear.Checked) txtAnyClaim.Text = "1";
                if (rdoYesCTPL.Checked || rdoNoCTPL.Checked) txtCTPL.Text = "1";

                Page.Form.DefaultButton = ibtNext.UniqueID;

                #endregion

                #region Sorting

                if (Session[General.UserId] != null)
                {
                    Cache.Remove("CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString());
                }
                else
                {
                    Cache.Remove("CarResult" + Session[General.CarId].ToString());
                }

                if (ViewState["SortOrder"] == null)
                {
                    ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                }

                if (ViewState["SortExpression"] == null)
                {
                    ViewState["SortExpression"] = "";
                }

                if (Request.Params["sortby"] != null)
                {
                    int _sortBy = 0;
                    if (Int32.TryParse(Request.Params["sortby"].ToString(), out _sortBy))
                    {
                        string _sortExpress = "";
                        string _sortOrder = "";

                        if (_sortBy == 0)
                        {
                            _sortExpress = "AnnualPremium";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 1)
                        {
                            _sortExpress = "CompanyName";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 2)
                        {
                            _sortExpress = "PackageName";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 3)
                        {
                            _sortExpress = "TPPD";
                            _sortOrder = " DESC";
                        }
                        else if (_sortBy == 4)
                        {
                            _sortExpress = "TPBIP";
                            _sortOrder = " DESC";
                        }
                        else if (_sortBy == 5)
                        {
                            //_sortExpress = "CashAllowance";
                            _sortExpress = "PADriver";
                            _sortOrder = " DESC";
                        }
                        else if (_sortBy == 6)
                        {
                            _sortExpress = "PAPassenger";
                            _sortOrder = " ASC";
                        }
                        else if (_sortBy == 7)
                        {
                            _sortExpress = "MedicalExpense";
                            _sortOrder = " ASC";
                        }
                        else
                        {
                            _sortExpress = "BailBond";
                            _sortOrder = " ASC";
                        }

                        ViewState["SortExpression"] = _sortExpress;
                        if (_sortOrder == " ASC")
                            ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                        else
                            ViewState["SortOrder"] = SortDirection.Descending.ToString();
                    }
                    else
                    {
                        ViewState["SortExpression"] = "AnnualPremium";
                        //ViewState["SortOrder"] = " ASC";
                        ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                    }
                }
                else
                {
                    ViewState["SortExpression"] = "PromotionPrice";
                    //ViewState["SortOrder"] = " ASC";
                    ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                }

                #endregion

                //NEED TO EDIT
                ResultsQuotesDataBind();

                General.ClearAllSession(this.Page, "CI");
            }
        }
        ClickOnceButton(this.Page, this.ibtNext);
    }

    private void LogUserViewedHistoryResult()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        _userviewdb.LogResultViewedHistory("CI", Request, "Car Insurance results.");
    }

    private void ShowQuoteSummary()
    {
        CarDetailTH _cardetail = new CarDetailTH();
        CarPolicy _carpolicy = new CarPolicy();

        CarDetailTHDB _cardetaildb = new CarDetailTHDB();
        CarPolicyDB _carpolicydb = new CarPolicyDB();

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();

        Int64 _refceuserid = 0;
        Int64 _carid = 0;

        if (Session[General.UserId] != null)
        {
            _refceuserid = Convert.ToInt64(Session[General.UserId].ToString());
        }

        if (Session[General.CarId] != null)
        {
            _carid = Convert.ToInt64(Session[General.CarId].ToString());
            _cardetail = _cardetaildb.GetCar(_carid, _refceuserid);
        }       
        _carpolicy = _carpolicydb.GetCarPolicy(_carid, _refceuserid);

        if (_cardetail != null && _carpolicy != null)
        {           
            lblYrofManufacture.Text = _cardetail.ManufactYear.ToString();
            lblYrofManTop.Text = _cardetail.ManufactYear.ToString();

            lblCarMakemodel.Text = _cardetail.MakeModelDesc;
            lblCarMakemodelTop.Text = _cardetail.MakeModelDesc;
            if (lblCarMakemodelTop.Text.Length > 40)
            {
                lblCarMakemodelTop.Font.Size = new FontUnit(8.0d);
                lblCarMakemodelTop.ToolTip = _cardetail.MakeModelDesc;
            }

            switch (_carpolicy.InsuranceType)
            {
                case 10: //class 1
                    lblInsuranceType.Text = "1";
                    ddlInsuranceType.SelectedIndex = ddlInsuranceType.Items.IndexOf(ddlInsuranceType.Items.FindByValue("10"));
                    rdoNoCTPL.Checked = true;
                    break;
                case 11: //class 1 (low cost)
                    lblInsuranceType.Text = "1+";
                    ddlInsuranceType.SelectedIndex = ddlInsuranceType.Items.IndexOf(ddlInsuranceType.Items.FindByValue("10"));
                    rdoNoCTPL.Checked = true;
                    break;
                case 21: //class 2+
                    lblInsuranceType.Text = "2+";
                    ddlInsuranceType.SelectedIndex = ddlInsuranceType.Items.IndexOf(ddlInsuranceType.Items.FindByValue("21"));
                    rdoNoCTPL.Checked = true;                    
                    divProvinceofRegistration.Style.Add("display", "none");
                    idAnyClaimLastYear.Style.Add("display", "none");
                    divDriver.Style.Add("display", "none");
                    divYesAccMod.Style.Add("display", "none");
                    break;
                case 31: //class 3+
                    lblInsuranceType.Text = "3+";
                    ddlInsuranceType.SelectedIndex = ddlInsuranceType.Items.IndexOf(ddlInsuranceType.Items.FindByValue("31"));
                    rdoNoCTPL.Checked = true;
                    divProvinceofRegistration.Style.Add("display", "none");
                    idAnyClaimLastYear.Style.Add("display", "none");
                    divDriver.Style.Add("display", "none");
                    divYesAccMod.Style.Add("display", "none");
                    break;
                case 30: //class 3
                    lblInsuranceType.Text = "3";
                    ddlInsuranceType.SelectedIndex = ddlInsuranceType.Items.IndexOf(ddlInsuranceType.Items.FindByValue("30"));

                    divCTPL.Style.Add("display", "");
                    divGarageType.Style.Add("display", "none");

                    divProvinceofRegistration.Style.Add("display", "none");
                    idAnyClaimLastYear.Style.Add("display", "none");
                    divDriver.Style.Add("display", "none");
                    divYesAccMod.Style.Add("display", "none");
                    divDeduct.Style.Add("display", "none");
                    break;
            }
            //Foreigner Case - send Mail 
            if (_cardetaildb.GetForeignerCase(_cardetail.Info8, _cardetail.Info7) > 0)
            {
                //SendMailNotification(_cardetail);
            }

            txtAccModAmount.Attributes.Add("onblur", "ShowValidationEffectThree('" + txtAccModAmount.ClientID + "','" + rfvAccModAmount.ClientID + "','" + revAccModAmount.ClientID + "','" + csvAccModAmount.ClientID + "');");
            ddlInsuranceType.Attributes.Add("onblur", "ShowValidationEffect('" + ddlInsuranceType.ClientID + "','" + rfvInsuranceType.ClientID + "');");
            ddlGarageType.Attributes.Add("onblur", "ShowValidationEffect('" + ddlGarageType.ClientID + "','" + rfvGarageType.ClientID + "');");

            ddlManufactYear.Attributes.Add("onblur", "ShowValidationEffect('" + ddlManufactYear.ClientID + "','" + rfvManufactYear.ClientID + "');");
            ddlCarMake.Attributes.Add("onblur", "ShowValidationEffect('" + ddlCarMake.ClientID + "','" + rfvCarMake.ClientID + "');");
            ddlModelBodyCCDoor.Attributes.Add("onblur", "ShowValidationEffect('" + ddlModelBodyCCDoor.ClientID + "','" + rfvModelBodyCCDoor.ClientID + "');");
            ddlVehicleType.Attributes.Add("onblur", "ShowValidationEffect('" + ddlVehicleType.ClientID + "','" + rfvVehicleType.ClientID + "');");
            ddlProvinceRegistration.Attributes.Add("onblur", "ShowValidationEffect('" + ddlProvinceRegistration.ClientID + "','" + rfvProvinceRegistration.ClientID + "');");

            ddlNCB.Attributes.Add("onblur", "ShowValidationEffect('" + ddlNCB.ClientID + "','" + rfvNCB.ClientID + "');");
            ddlNCB.Attributes.Add("onfocus", "JT_ShowTwo('" + Resources.CarInsuranceToolTips.NCBDisclaimer + "', '" + ddlNCB.ClientID + "', '" + Resources.CarInsurance.NCB + "'); return true;");
            ddlNCB.Attributes.Add("onblur", "$('#JT').remove();ShowValidationEffect('" + ddlNCB.ClientID + "','" + rfvNCB.ClientID + "');");

            txtEmailAddress.Attributes.Add("onblur", "ShowValidationEffectTwo('" + txtEmailAddress.ClientID + "','" + rfvEmail.ClientID + "','" + rfvEmailValid.ClientID + "');");

        }

        _profile = null;
        _profiledb = null;
        _cardetail = null;
        _cardetaildb = null;
        _carpolicy = null;
        _carpolicydb = null;
    }

    private bool CheckViewCount()
    {
        MyDatabase _db = new MyDatabase();
        string _spName = "[sprocCarInsuranceResultViewCountByDateUpdateSingleItem]";

        SortedList _spList = new SortedList();
        _spList.Add("@RefCEUserId", Session[General.UserId].ToString());
        Int64 _retValue = _db.ExecuteSP(_spName, _spList);
        return _retValue > 0;
    }
    
    
    private Int32 CalculatePremium()
    {
        int _result = 0;
        MyDatabase _db = new MyDatabase();
        SortedList _sPara = new SortedList();

        Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
        Int64 _userId = 0;
        if (Session[General.UserId] != null)
        {
            _userId = Convert.ToInt64(Session[General.UserId].ToString());
        }
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        _sPara.Add("@RefUserId", _userId);

        _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceClear]", _sPara);

        //select car detail
        _db = new MyDatabase();
        _sPara = new SortedList();
        DataTable _dt = new DataTable("tblModelBody");
        _sPara.Add("@CarId", Session[General.CarId].ToString());
        _sPara.Add("@RefCEUserId", _userId);
        _dt = _db.GetDataTableBySP("[sprocCarDetailTHSelectSingleItem]", _sPara);
        string[] makeName;
        makeName = _dt.Rows[0]["MakeModelDesc"].ToString().Split(' ');

        if (_dt.Rows.Count > 0)
        {
            #region KawnaPackage
            try
            {
                if (IsKawnaCar(makeName[0]))
                {
                    DataTable dtPackage = new DataTable();

                    CarPolicy _carpolicy = new CarPolicy();
                    CarPolicyDB _carpolicydb = new CarPolicyDB();
                    _carpolicy = _carpolicydb.GetCarPolicy(_carId, _userId);
                    string strProviderList = "";

                    string strCarProvince = _carpolicy.ProvinceRegistration == "BKK" ? "1" : "79";
                    string strDriverAge1 = "", strDriverAge2 = "";
                    int DriverAge1 = 0, DriverAge2 = 0;
                    if (_carpolicy.IsAddDriver == true)
                    {
                        CarDriverList _cardriverlist = new CarDriverList();
                        CarDriverDB _cardriverdb = new CarDriverDB();
                        _cardriverlist = _cardriverdb.GetCarDriverList(_carId, _userId);
                        _cardriverdb = null;
                        int _noOfDriver = _carpolicy.NoOfDriver;
                        for (int i = 1; i <= _noOfDriver; i++)
                        {
                            CarDriver _cardriver = _cardriverlist[i - 1];
                            if (i == 1)
                            {
                                DriverAge1 = General.GetUTCDateTime().Year - _cardriver.DOB.Year;
                            }
                            else if (i == 2)
                            {
                                DriverAge2 = General.GetUTCDateTime().Year - _cardriver.DOB.Year;
                            }
                        }
                        _cardriverlist = null;

                        if (DriverAge1 >= 18 && DriverAge1 <= 24)
                            strDriverAge1 = "18";
                        else if (DriverAge1 >= 25 && DriverAge1 <= 35)
                            strDriverAge1 = "25";
                        else if (DriverAge1 >= 36 && DriverAge1 <= 50)
                            strDriverAge1 = "36";
                        else if (DriverAge1 > 50)
                            strDriverAge1 = "50";

                        if (_noOfDriver == 2)
                        {
                            if (DriverAge2 >= 18 && DriverAge2 <= 24)
                                strDriverAge2 = "18";
                            else if (DriverAge2 >= 25 && DriverAge2 <= 35)
                                strDriverAge2 = "25";
                            else if (DriverAge2 >= 36 && DriverAge2 <= 50)
                                strDriverAge2 = "36";
                            else if (DriverAge2 > 50)
                                strDriverAge2 = "50";
                        }

                    }

                    HttpWebRequest request;
                    string kawnaModel = GetKawnaModelValue(makeName[0], _dt.Rows[0]["CarModel"].ToString() + " " + String.Format("{0:0.0}", (Convert.ToInt32(_dt.Rows[0]["CC"]) * 0.001)) + "cc " + _dt.Rows[0]["Door"].ToString() + " Door");
                    string tun = GetKawnaSingleSumInsured(makeName[0], kawnaModel, _dt.Rows[0]["ManufactYear"].ToString());
                    if (tun == "0") tun = "";
                    string url = _url + "?brand=" + makeName[0].ToString() + "&id_motor=" + kawnaModel.ToString() + "&yearcar=" + _dt.Rows[0]["ManufactYear"].ToString() + "&tun=" + tun + "&Yins=0&dee=0&country=" + strCarProvince + "&rgb=" + strCarProvince + "&paper=no&plantry=&oldinsure=&clame=" + (_carpolicy.IsClaimLastYear == false ? "ไม่มีเครม" : "มีเครม+ไม่มีคู่กรณี") + "&rabu=" + (_carpolicy.IsAddDriver == true ? "yes" : "") + "&old1=" + strDriverAge1 + "&old2=" + strDriverAge2 + "&t=submit";
                    string responseBody = string.Empty;
                    string requestBody = "";
                    byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestBody.ToString());
                    request = (HttpWebRequest)HttpWebRequest.Create(url);
                    request.ContentType = "application/xml;charset=utf-8";
                    //request.ContentType = "text/xml;charset=utf-8";
                    request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
                    request.Accept = "*/*";
                    request.Method = "POST";
                    request.ContentLength = byteData.Length;
                    System.Net.ServicePointManager.Expect100Continue = false;
                    request.KeepAlive = false;

                    string startTime = DateTime.Now.ToString("HH:mm:ss.ff tt dd/MM/yyyy");
                    DateTime sTime = DateTime.Now;
                    DataTable dtIns = new DataTable();
                    DataSet ds = new DataSet();
                    using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                    {
                        ds.ReadXml(response.GetResponseStream());
                    }
                    dtPackage = ds.Tables["Pre"];
                    DataTable dt = ds.Tables["INS"];
                    dtIns = dt.Clone();
                    dtIns = dt.Copy();

                    // *** Start Join Table ***
                    DataTable dtblResult = dtPackage.Clone();
                    dtblResult.Columns.Add("InsName", typeof(string));
                    dtblResult.Columns.Add("INS_Text", typeof(string));
                    dtblResult.Columns.Add("PRE_IdIns", typeof(string));

                    //get row data
                    var rowData = from row1 in dtPackage.AsEnumerable()
                                  join row2 in dtIns.AsEnumerable()
                                  on row1["PRE_Id"] equals row2["PRE_Id"]
                                  select row1.ItemArray.Concat(row2.ItemArray).ToArray();

                    //Add row data to dtblResult
                    foreach (object[] values in rowData)
                        dtblResult.Rows.Add(values);

                    //Change column name back to original
                    dtblResult.Columns["INS_Text"].ColumnName = "INS";

                    //Remove extra column from result
                    dtblResult.Columns.Remove("PRE_IdIns");
                    dtblResult.Columns.Add("PROPRICE", typeof(Double));
                    dtPackage.Dispose();
                    dtPackage = new DataTable();
                    dtPackage = dtblResult.Clone();
                    dtPackage.Columns["PRICE"].DataType = typeof(string);
                    //dtPackage = dtblResult.Copy();
                    foreach (DataRow row in dtblResult.Rows)
                    {
                        dtPackage.ImportRow(row);
                    }

                    dtblResult.Dispose();
                    dtIns.Dispose();
                    // *** End Join Table ***

                    _db = new MyDatabase();
                    _sPara = new SortedList();
                    DataTable _dtPvdList = new DataTable();
                    _dtPvdList = _db.GetDataTable("SELECT ProviderId FROM tblKawnaProvider WHERE ProviderCompanyId IS NOT NULL");

                    foreach (DataRow dr in _dtPvdList.Rows)
                    {
                        if (strProviderList != null && strProviderList != "")
                            strProviderList += ",";
                        strProviderList += dr["ProviderId"];
                    }
                    var strExpr = " INS IN(" + strProviderList + ") ";

                    if (_carpolicy.InsuranceType == 10 || _carpolicy.InsuranceType == 11)
                        strExpr += " AND POTYPE = 'ป1' ";
                    else if (_carpolicy.InsuranceType == 21)
                        strExpr += " AND POTYPE = 'ป2+' ";
                    else if (_carpolicy.InsuranceType == 31)
                        strExpr += " AND POTYPE = 'ป3+' ";
                    else if (_carpolicy.InsuranceType == 30)
                        strExpr += " AND POTYPE = 'ป3' ";

                    if (_carpolicy.GarageType > 0 && _carpolicy.InsuranceType != 30)
                    {
                        strExpr += " AND FIX = ";
                        strExpr += _carpolicy.GarageType.ToString() != "1" ? "'ห้าง' " : "'อู่' ";
                    }

                    if (_carpolicy.InsuranceType != 30)
                    {
                        if (_carpolicy.Deductible == 0 && ddlDeduct.SelectedValue == "0")
                            strExpr += " AND (ODDD = '' OR ODDD IS NULL)";
                        else if (_carpolicy.Deductible > 0 || ddlDeduct.SelectedValue == "5000")
                            strExpr += " AND ODDD <> ''";
                    }

                    if (_carpolicy.InsuranceType == 30)
                    {
                        if (_carpolicy.IsCTPL == true)
                            strExpr += " AND (CMI_INCLUDE = 'yes' )";
                        else
                            strExpr += " AND (CMI_INCLUDE <> 'yes' )";
                    }


                    var strSort = " PRICE ASC, TUN ASC ";              
                    DataView dv = new DataView(dtPackage);

                    dv.RowFilter = strExpr;
                    dv.Sort = strSort;

                    var query = (from order in dv.ToTable().AsEnumerable()
                                 group order by order["INS"] into grp
                                 let fewItems = grp.Take(3).ToList()
                                 select fewItems.CopyToDataTable());

                    DataTable boundTable = new DataTable();
                    boundTable = dv.ToTable().Clone();
                    foreach (var rsv in query)
                    {
                        for (int i = 0; i < rsv.Rows.Count; i++)
                            boundTable.ImportRow(rsv.Rows[i]);
                    }
                    foreach (DataRow drc in boundTable.Rows)
                    {
                        _db = new MyDatabase();
                        _sPara = new SortedList();
                        _sPara.Add("FromSource", "W");
                        _sPara.Add("CarId", Convert.ToInt64(Session[General.CarId]));
                        _sPara.Add("ProviderId", drc["INS"].ToString() != "" ? Convert.ToInt32(drc["INS"]) : 0);
                        _sPara.Add("PackageId", drc["PACKID"].ToString() != "" ? Convert.ToInt32(drc["PACKID"]) : 0);
                        _sPara.Add("PackageName", drc["PACKNAME"].ToString());
                        _sPara.Add("TotalPremium", drc["PRICE"].ToString() != "" ? Convert.ToDouble(drc["PRICE"]) : 0.0);
                        _sPara.Add("TotalVMI", drc["PRICE"].ToString() != "" ? Convert.ToDouble(drc["PRICE"]) : 0.0);
                        _sPara.Add("IsIncludeCMI", drc["CMI_INCLUDE"].ToString() != "" ? true : false);
                        _sPara.Add("TPPD", drc["TP"].ToString() != "" ? (Convert.ToInt64(drc["TP"].ToString().Replace(",", ""))) : 0);
                        _sPara.Add("TPBIP", drc["BT"].ToString().ToString() != "" ? (Convert.ToInt64(drc["BT"].ToString().Replace(",", ""))) : 0);
                        _sPara.Add("TPBIA", drc["BI"].ToString().ToString() != "" ? (Convert.ToInt64(drc["BI"].ToString().Replace(",", ""))) : 0);
                        _sPara.Add("DEC", drc["ODDD"].ToString().Trim() != "" ? Convert.ToDouble(drc["ODDD"].ToString().Trim()) : 0);
                        _sPara.Add("SumInsured", drc["TUN"].ToString() != "" ? Convert.ToInt64(drc["TUN"].ToString()) : 0);
                        _sPara.Add("FireAndTheft", drc["FIRE"].ToString() != "" ? Convert.ToDouble(drc["FIRE"].ToString()) : 0.0);
                        _sPara.Add("Theft", drc["TUN"].ToString() != "" ? Convert.ToInt64(drc["TUN"].ToString()) : 0);
                        _sPara.Add("PADriver", drc["PA"].ToString() != "" ? (Convert.ToDouble(drc["PA"].ToString().Replace(",", ""))) : 0.0);
                        _sPara.Add("PAPassenger", drc["PA"].ToString() != "" ? (Convert.ToDouble(drc["PA"].ToString().Replace(",", ""))) : 0.0);
                        _sPara.Add("MED", drc["ME"].ToString() != "" ? (Convert.ToDouble(drc["ME"].ToString().Replace(",", ""))) : 0.0);
                        _sPara.Add("BailBond", drc["BB"].ToString() != "" ? (Convert.ToDouble(drc["BB"].ToString().Replace(",", ""))) : 0.0);
                        _sPara.Add("RefUserId", Convert.ToDouble(Session[General.UserId].ToString()));
                        _sPara.Add("IsSpecialOffer", 0);
                        _sPara.Add("IsFloodCover", drc["FLOOD"].ToString().Trim() != "" ? 1 : 0);
                        _sPara.Add("GarageType", drc["FIX"].ToString().Trim() != "" && drc["FIX"].ToString().Trim() == "ห้าง" ? 1 : 0);
                        _sPara.Add("CarType", _dt.Rows[0]["Body"].ToString());
                        _sPara.Add("CarDoors", _dt.Rows[0]["Door"].ToString() != "" ? Convert.ToInt32(_dt.Rows[0]["Door"].ToString()) : 4);
                        _sPara.Add("@PeopleCovered", drc["P"].ToString().Trim() != "" ? drc["P"].ToString().Trim() : "0");
                        _result = _db.ExecuteNonSqlSP("[sprocKawnaSaveResultPackages]", _sPara);

                    }
                    return _result;

                }
            }
            catch { }

            #endregion
            
                _db = new MyDatabase();
                _sPara = new SortedList();
                _sPara.Add("@CarId", Session[General.CarId].ToString());
                _sPara.Add("@RefUserId", _userId);

                BKIDetailDB bki = new BKIDetailDB();

                if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                        Convert.ToInt32(CE.Global.CEUserType.Provider) && Session[CE.Global.General.ProviderCompanyId] != null)
                {
                    if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AZCPProviderCompanyID"))
                        _result = _db.ExecuteNonSqlSP("[sprocAZCPCarInsuranceCalculation]", _sPara);
                    else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.AXAProviderCompanyID"))
                        _result = _db.ExecuteNonSqlSP("[sprocAXACarInsuranceCalculation]", _sPara);
                    else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.MSIGProviderCompanyID"))
                        _result = _db.ExecuteNonSqlSP("[sprocMSIGCarInsuranceCalculation]", _sPara);
                    else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.LMGProviderCompanyID"))
                        _result = _db.ExecuteNonSqlSP("[sprocLMGCarInsuranceCalculation]", _sPara);
                    else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ChartisProviderCompanyID"))
                        _result = _db.ExecuteNonSqlSP("[sprocChartisCarInsuranceCalculation]", _sPara);
                    else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.ThaivivatProviderCompanyID"))
                        _result = _db.ExecuteNonSqlSP("[sprocTVVCarInsuranceCalculation]", _sPara);
                    else if (Session[CE.Global.General.ProviderCompanyId].ToString() == CE.Configuration.MyConfigurationManager.GetAppSettingValue("TH.BKIProviderCompanyID"))
                    {
                        try
                        {
                            bki.BKICalculation(_carId, _userId);
                        }
                        catch
                        {
                        }

                        _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculationBKI]", _sPara);
                    }
                }
                else
                {
                    //====Test Web Service
                    try
                    {
                        bki.BKICalculation(_carId, _userId);
                    }
                    catch
                    {
                    }

                    _result = _db.ExecuteNonSqlSP("[sprocProviderCarInsuranceCalculation]", _sPara);
                }
                return _result;
            //}
        }
        return 0;
    }

    #region kawna
    private string _url = "http://www.kawna.com/dat/qMotor2.php";
    DataSet dsBrand = new DataSet();
    private bool IsKawnaCar(string makeName)
    {
        try
        {
            HttpWebRequest request;
            //HttpWebResponse hwResponse;
            string url = _url + "?t=b";
            string responseBody = string.Empty;
            string requestBody = "";
            byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestBody.ToString());
            request = (HttpWebRequest)HttpWebRequest.Create(url);
            request.ContentType = "application/xml;charset=utf-8";
            //request.ContentType = "text/xml;charset=utf-8";
            request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
            request.Accept = "*/*";
            request.Method = "POST";
            request.ContentLength = byteData.Length;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                dsBrand.ReadXml(response.GetResponseStream());
            }

            foreach (DataRow dr in dsBrand.Tables[0].Rows)
            {
                if (dr["B_Text"].ToString().ToLower() == makeName.ToLower())
                    return true;
            }
        }
        catch
        {
            return false;
        }
        return false;
    }

    DataSet dsModel = new DataSet();
    private string GetKawnaModelValue(string brandName, string modelName)
    {
        HttpWebRequest request;
        string url = _url + "?t=m&b=" + brandName;
        string responseBody = string.Empty;
        string requestBody = "";
        byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestBody.ToString());
        request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.ContentType = "application/xml;charset=utf-8";
        //request.ContentType = "text/xml;charset=utf-8";
        request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
        request.Accept = "*/*";
        request.Method = "POST";
        request.ContentLength = byteData.Length;
        System.Net.ServicePointManager.Expect100Continue = false;
        request.KeepAlive = false;
        DataSet dsM = new DataSet();
        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
            dsM.ReadXml(response.GetResponseStream());
        }
        foreach (DataRow dr in dsM.Tables[0].Rows)
        {
            if (dr["M_Text"].ToString().ToLower() == modelName.ToLower())
                return dr["value"].ToString();
        }
        return "0";
    }
    /// <summary>
    /// Get Minimum Kawna SumInsured
    /// </summary>
    /// <param name="cmake"></param>
    /// <param name="cmodel"></param>
    /// <param name="cyear"></param>
    /// <returns></returns>
    private string GetKawnaSingleSumInsured(string cmake,string cmodel,string cyear)
    {
        HttpWebRequest request;
        string url = _url + "?t=t&b=" + cmake.Trim() + "&m=" + cmodel.Trim() + "&y=" + cyear.Trim();
        string responseBody = string.Empty;
        string requestBody = "";
        byte[] byteData = UTF8Encoding.UTF8.GetBytes(requestBody.ToString());
        request = (HttpWebRequest)HttpWebRequest.Create(url);
        request.ContentType = "application/xml;charset=utf-8";
        //request.ContentType = "text/xml;charset=utf-8";
        request.UserAgent = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0; BOIE9;ENUS)";
        request.Accept = "*/*";
        request.Method = "POST";
        request.ContentLength = byteData.Length;
        System.Net.ServicePointManager.Expect100Continue = false;
        request.KeepAlive = false;

        DataSet dsS = new DataSet();
        using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
        {
            dsS.ReadXml(response.GetResponseStream());
        }

        if (dsS.Tables[0].Rows.Count == 1 && dsS.Tables[0].Rows[0][0].ToString() == "ERR4")
        {
           // Alert("ไม่พบทุน ของรถรุ่น " +cmodel + " ในปี " + cyear);
        }
        else
        {
            return dsS.Tables[0].Rows[0][0].ToString();
        }

        return "";
    }

   #endregion

    private void ResultsQuotesDataBind()
    {
        GetTempResultTableTwo();
        DataView dv = new DataView();
        if (Session[General.UserId] != null)
        {
            dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);
        }
        else
        {
            dv = new DataView((DataTable)Cache["CarResult" + Session[General.CarId].ToString()]);
        }

        string _strSort = "";
        if (ViewState["SortOrder"].ToString() == SortDirection.Ascending.ToString())
        {
            _strSort = " ASC";
        }
        else
        {
            _strSort = " DESC";
        }
        dv.Sort = ViewState["SortExpression"].ToString() + _strSort;
        
        rptCarResult.DataSource = dv;
        rptCarResult.DataBind();
    }

    private void SortGridViews(string strExpression)
    {
        if (Session[General.UserId] != null)
        {
            if (Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] == null)
            {
                GetTempResultTableTwo();
            }
        }
        else
        {
            if (Cache["CarResult" + Session[General.CarId].ToString()] == null)
            {
                GetTempResultTableTwo();
            }
        }

        if (ViewState["SortOrder"] == null)
        {
            ViewState["SortOrder"] = SortDirection.Descending;
        }

        if (ViewState["SortExpression"] == null)
        {
            ViewState["SortExpression"] = SortDirection.Ascending.ToString();
        }

        DataView dv = new DataView();

        if (Session[General.UserId] != null)
        {
            dv = new DataView((DataTable)Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()]);
        }
        else
        {
            dv = new DataView((DataTable)Cache["CarResult" + Session[General.CarId].ToString()]);
        }
        string strSort = "";
        if (ViewState["SortOrder"].ToString() == SortDirection.Ascending.ToString())
        {
            if (ViewState["SortExpression"].ToString() == strExpression)
            {
                strSort = " DESC";
                ViewState["SortOrder"] = SortDirection.Descending.ToString();
                ViewState["SortExpression"] = strExpression;
            }
            else
            {
                strSort = " ASC";
                ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                ViewState["SortExpression"] = strExpression;
            }

        }
        else
        {
            if (ViewState["SortExpression"].ToString() == strExpression)
            {
                strSort = " ASC";
                ViewState["SortOrder"] = SortDirection.Ascending.ToString();
                ViewState["SortExpression"] = strExpression;
            }
            else
            {
                strSort = " DESC";
                ViewState["SortOrder"] = SortDirection.Descending.ToString();
                ViewState["SortExpression"] = strExpression;
            }

        }

        dv.Sort = strExpression + strSort;

        rptCarResult.DataSource = dv;
        rptCarResult.DataBind();

    }

    private void GetTempResultTableTwo()
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dtResult = new DataTable();
        string _spName = "[sprocCarInsuranceResultSelectItemList]";
        SortedList _sPara = new SortedList();
        _sPara.Add("@CarId", Session[General.CarId].ToString());

        if (Session[General.UserId] != null)
        {
            _sPara.Add("@RefUserId", Session[General.UserId].ToString());
        }
        else
        {
            _sPara.Add("@RefUserId", 0);
        }
        _dtResult = _db.GetDataTableBySP(_spName, _sPara);
        if (_dtResult.Rows.Count > 0)
        {
        }
        else
        {
            Session["UMMSG"] = "CI,5000";
        }

        if (Session[General.UserId] != null)
        {
            Cache["CarResult" + Session[General.UserId].ToString() + Session[General.CarId].ToString()] = _dtResult;
        }
        else
        {
            Cache["CarResult" + Session[General.CarId].ToString()] = _dtResult;
        }
    }

    protected int GetRowNumber(string ctrlId)
    {
        int num = ctrlId.LastIndexOf("ctl");
        string index = ctrlId.Substring(num + 3, 2);
        int resultTemp = 0;
        int result = -1;
        if (int.TryParse(index, out resultTemp))
        {
            result = resultTemp;
        }
        return result;
    }

    private void LogUserSelectHistory(Int64 ResultId, Int64 CompanyId)
    {
        UserSelectHistoryDB _userselectdb = new UserSelectHistoryDB();
        _userselectdb.LogUserSelectHistory("CI", Request.Browser.Type, Request.UserHostAddress, "CI", ResultId, CompanyId);
    }

    public string GetFilePath()
    {
        string _filePath = CE.Configuration.MyConfigurationManager.GetAppSettingValue("FileOutputPath").ToString();
        _filePath += "exceloutput\\car_nomatch\\";
        CE.InputOut.MyIO _myIO = new CE.InputOut.MyIO();
        string _todaydate = General.GetUTCDateTime().ToString("yyyyMMMdd");
        if (!_myIO.CheckDirectory(_filePath + _todaydate))
        {
            if (_myIO.CreateDirectory(_filePath, _todaydate))
            {
                _filePath += _todaydate + "\\";
            }
        }
        else
        {
            _filePath += _todaydate + "\\";
        }

        return _filePath;
    }
    
    protected void rptCarResult_ItemCommand(object sender, RepeaterCommandEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            HyperLink hplDetails = (HyperLink)e.Item.FindControl("hplDetails");
        }
        if (e.CommandName.ToLower().Equals("moreinfo"))
        {
            Label lblProviderId = (Label)e.Item.FindControl("lblProviderId");
            Session[CE.Global.General.ProviderCompanyId] = lblProviderId.Text;
            Label lblTempResultId = (Label)e.Item.FindControl("lblTempResultId");
            Session[CE.Global.General.CarResultId] = lblTempResultId.Text;

            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/quote-details.aspx", Page);
            Response.Redirect(_redirectUrl);
        }
        else if (e.CommandName.ToLower().Equals("callfordiscount"))
        {
            Label lblProviderId = (Label)e.Item.FindControl("lblProviderId");
            Session[CE.Global.General.ProviderCompanyId] = lblProviderId.Text;
            Label lblTempResultId = (Label)e.Item.FindControl("lblTempResultId");
            Session[CE.Global.General.CarResultId] = lblTempResultId.Text;
            Image imgPackageName = (Image)e.Item.FindControl("imgProvider");
            string strInsType = "";
            if (lblInsuranceType.Text == "1")
            {
                strInsType = "10";
            }
            else if (lblInsuranceType.Text == "2+")
            {
                strInsType = "21";
            }
            else if (lblInsuranceType.Text == "3")
            {
                strInsType = "30";
            }
            else if (lblInsuranceType.Text == "3+")
            {
                strInsType = "31";
            }
            if (Session[General.UserId] != null)
            {
                rdoExistingYes.Checked = true;
            }
            hidProvider.Value = lblProviderId.Text;
            ShowCallPopup();
            mpeCallPop.Show();
        }
        else if (e.CommandName.ToLower().Equals("buyonline"))
        {
            Label lblProviderId = (Label)e.Item.FindControl("lblProviderId");
            Session[CE.Global.General.ProviderCompanyId] = lblProviderId.Text;
            Label lblTempResultId = (Label)e.Item.FindControl("lblTempResultId");
            Session[CE.Global.General.CarResultId] = lblTempResultId.Text;

            Response.Redirect(SetBuyNowUrl(lblProviderId.Text));
        }
        else if (e.CommandName.ToLower().Equals("compare"))
        {
            Label lblProviderId = (Label)e.Item.FindControl("lblProviderId");
            Session[CE.Global.General.ProviderCompanyId] = lblProviderId.Text;
            Label lblTempResultId = (Label)e.Item.FindControl("lblTempResultId");
            Session[CE.Global.General.CarResultId] = lblTempResultId.Text;
            Session["CITempResultId"] = hidStrResultCompare.Value;
            Response.Redirect(CE.Global.General.GetUrl("~/car-insurance/CompareInsurance.aspx", Page));
        }
    }

    private void ShowCallPopup()
    {
        Int64 UserId = Convert.ToInt64(Session[General.UserId]);
        _profile = new CE.User.Profile();
        _profiledb = new ProfileDB();
        _contact = new Contact();
        _contactdb = new ContactDB();

        _profile = _profiledb.GetProfile(UserId);
        _profiledb = null;

        if (_profile != null)
        {
            txtCallMeFullNamePop.Text = _profile.FirstName + " " + _profile.SurName;


            _contact = _contactdb.GetContact(UserId);
            if (_contact != null)
            {
                usrCallMePhoneNo.PhoneNo = _contact.Mobile;
                txtEmailPop.Text = _contact.Email;
                txtEmailPop.ReadOnly = true;

            }

            _profile = null;
        }
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (usrCallMePhoneNo.GetPhoneNo().Length == 10)
        {
            string _message = "";
            string _title = "";

            txtCallMeFullNamePop.Text = General.ClearScriptTag(txtCallMeFullNamePop.Text);
            _message = "Customer Name: " + Server.HtmlEncode(txtCallMeFullNamePop.Text);
            _title = "Call Me Now - Call Me request by " + Server.HtmlEncode(txtCallMeFullNamePop.Text);
            ChangeValidationEffectServerSide("callme");
            if (IsValid)
            {
                Int64 _result = 0;
                ContactUser _cu = new ContactUser();
                ContactUserDB _cudb = new ContactUserDB();

                string strInsType = lblInsuranceType.Text;

                _cu.InsuranceType = "CI-" + strInsType;


                _cu.ProductId = Convert.ToInt64(Session[General.CarId].ToString());
                _cu.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());

                _cu.ProviderCompanyId = Convert.ToInt64(hidProvider.Value);
                _cu.ContactNo = usrCallMePhoneNo.GetPhoneNo();
                _cu.FullName = Server.HtmlEncode(txtCallMeFullNamePop.Text);
                _cu.CallTime = Convert.ToInt16(ddlCallMeTime.Text);

                if (Request.Params["spc"] != null)
                {
                    if (Request.Params["spc"].ToString() == "1")
                    {
                        _cu.Info1 = "GG Promotion";
                    }
                }

                _result = _cudb.Insert(_cu);

                if (_result > 0)
                {
                    _profile = new CE.User.Profile();
                    _profiledb = new ProfileDB();
                    _profile = _profiledb.GetProfile(_cu.RefCEUserId);
                    if (_profile != null && _profile.ProfileId > 0)
                    {
                        _profile.SurName = string.Empty;
                        _profile.FirstName = Server.HtmlEncode(txtCallMeFullNamePop.Text);
                        _profiledb.Insert(_profile);
                    }
                    _profile = null;
                    _profiledb = null;

                    _contact = new Contact();
                    _contactdb = new ContactDB();
                    _contact = _contactdb.GetContact(_cu.RefCEUserId);
                    if (_contact != null && _contact.ContactId > 0)
                    {
                        _contact.Mobile = usrCallMePhoneNo.GetPhoneNo();
                        _contactdb.Insert(_contact);
                    }
                    _contact = null;
                    _contactdb = null;

                    CE.CarInsurance.CarDetailTH _cardetail = new CE.CarInsurance.CarDetailTH();
                    CE.CarInsurance.CarDetailTHDB _cardetailDB = new CE.CarInsurance.CarDetailTHDB();
                    _cardetail = _cardetailDB.GetCar(_cu.ProductId, _cu.RefCEUserId);
                    if (_cardetail != null && _cardetail.CarId > 0)
                    {
                        _cardetail.Info7 = string.Empty;
                        _cardetail.Info8 = Server.HtmlEncode(txtCallMeFullNamePop.Text);
                        _cardetailDB.Insert(_cardetail);
                    }
                    _cardetail = null;
                    _cardetailDB = null;
                    ScriptManager.RegisterStartupScript(Page, this.GetType(), "alertThxU", "alert('" + Resources.CarInsurance.CallMeMessage + "')", true);
                    
                    _message += "<img src='http://www.gluaygluay.com/images/callme/callme-home.png' /><br/>";
                    _message += "<br/><br/>Insurance Type : " + strInsType;
                    _message += "<br/><br/>Full Name : " + Server.HtmlEncode(txtCallMeFullNamePop.Text);
                    _message += "<br/><br/>Email : " + txtEmailPop.Text;
                    _message += "<br/><br/>Contact No : " + usrCallMePhoneNo.GetPhoneNo();
                    _message += "<br/><br/>Call Time : " + ddlCallMeTime.SelectedItem.Text;
                    string _emailList = ConfigurationManager.AppSettings["TH.CICallMeMessageReceiver"].ToString();
                    MyMailManager.SendCRMMessage(_emailList, _title, _message);

                    divCallMe.Visible = true;
                    lblCallMeMessage.Text = Resources.CarInsurance.CallMeMessage;

                    txtCallMeFullNamePop.ReadOnly = true;
                    txtEmailPop.ReadOnly = true;
                    ddlCallMeTime.Enabled = false;
                    usrCallMePhoneNo.IsEnabled = false;
                    btnSubmit.Enabled = false;


                }
            }
        }

    }

    protected void rptCarResult_ItemDataBound(object sender, RepeaterItemEventArgs e)
    {
        if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
        {
            Button btnFindMore = (Button)e.Item.FindControl("btnFindMore");
            Button btnCompare = (Button)e.Item.FindControl("btnCompare");
            Label lblDeductible = (Label)e.Item.FindControl("lblDeductible");
            Label lblTempResultId = (Label)e.Item.FindControl("lblTempResultId");
            Label lblPackageName = (Label)e.Item.FindControl("lblPackageName");
            bool IsEng = false;
            foreach (char ch in lblPackageName.Text.Trim().ToCharArray())
            {
                int x = (int)ch;
                if (x >= 63 && x <= 126)
                {
                    IsEng = true;
                    break;
                }
                else
                {
                    break;
                }
            }

            if (IsEng)
            {
                if (lblPackageName.Text.Trim().Length > 30)
                {
                    lblPackageName.Text = lblPackageName.Text.Trim().Substring(0, 30) + "...";
                }
            }
            else
            {
                if (lblPackageName.Text.Trim().Length > 30)
                {
                    lblPackageName.Text = lblPackageName.Text.Trim().Substring(0, 30) + "...";
                }
            }

            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "DEC")) > 0)
            {
                lblDeductible.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "DEC")).ToString("#,000");
            }
            else
            {
                lblDeductible.Text = Resources.CarInsuranceResultPage.Waived;
            }

            Label lblSumInsured = (Label)e.Item.FindControl("lblSumInsured");
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "SumInsured")) > 0 )
            {
                lblSumInsured.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "SumInsured")).ToString("#,000");
            }
            else
            {
                lblSumInsured.Text = " - ";
            }
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "IsFloodCover")) == 0)
            {
                
                HtmlGenericControl divflood = (HtmlGenericControl)(e.Item.FindControl("divFlood"));
                divflood.Visible = false;
                    
            }
            Label lblAnnualPremium = (Label)e.Item.FindControl("lblAnnualPremium");
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "AnnualPremium")) > 0)
            {
                lblAnnualPremium.Text = Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "AnnualPremium")).ToString("#000.00");
            }

            Label lblDiscount = (Label)e.Item.FindControl("lblDiscount");
            Label lblPremiumPrice = (Label)e.Item.FindControl("lblPremiumPrice");
            if (Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "AnnualPremium")) == Convert.ToInt32(DataBinder.Eval(e.Item.DataItem, "PromotionPrice")))
            {
                HtmlGenericControl divDiscount = (HtmlGenericControl)(e.Item.FindControl("divDiscount"));
                divDiscount.Visible = false;
                lblPremiumPrice.Visible = false;
                
            }
            else
            {    
            }

            Image imgProvider = (Image)e.Item.FindControl("imgProvider");
            HtmlGenericControl divSpecialNCB = (HtmlGenericControl)e.Item.FindControl("divSpecialNCB");
            if (imgProvider.AlternateText == "GluayGluay.com Special")
            {
                imgProvider.ImageUrl = "/images/public/gluaygluay_logo.png";
                HtmlImage imgS = (HtmlImage)e.Item.FindControl("imgSpecial");
                imgS.Style.Add("display", "");
                divSpecialNCB.Style.Add("display", "");
            }
        }
    }

    private string SetBuyNowUrl(string providerid)
    {
        string _redirectUrl = string.Empty;
        if (providerid == "11")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/azcp_proposal_form.aspx", Page);
        }
        else if (providerid == "12")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/msig_proposal_form.aspx", Page);
        }
        else if (providerid == "16")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/axa_proposal_form.aspx", Page);
        }
        else if (providerid == "29")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/lmg_proposal_form.aspx", Page);
        }
        else if (providerid == "31")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/chartis_proposal_form.aspx", Page);
        }
        else if (providerid == "32")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/bki_proposal_form.aspx", Page);
        }
        else if (providerid == "33")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/mti_proposal_form.aspx", Page);
        }
        else if (providerid == "35")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/krungthai_proposal_form.aspx", Page);
        }
        else if (providerid == "39")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/mittare_proposal_form.aspx", Page);
        }
        else if (providerid == "41")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/ksk_proposal_form.aspx", Page);
        }
        else if (providerid == "43")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/synmunkong_proposal_form.aspx", Page);
        }
        else if (providerid == "45")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/viriyah_proposal_form.aspx", Page);
        }
        else if (providerid == "46")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/tms_proposal_form.aspx", Page);
        }
        else if (providerid == "50")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/scsmg_proposal_form.aspx", Page);
        }
        else if (providerid == "58")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/tvv_proposal_form.aspx", Page);
        }
        else if (providerid == "65")
        {
            _redirectUrl = CE.Global.General.GetUrl("~/car-insurance/proposalforms/dhipaya_proposal_form.aspx", Page);
        }
        return _redirectUrl;
    }

    #region SearchQuote

    protected void btnNext_Click(object sender, EventArgs e)
    {
        OtherValidation();
        //DriverValidation();
        ChangeValidationEffectServerSide("cardetail");

        Page.Validate("cardetail");
        if (Page.IsValid)
        {
            if (Save())
            {
                Int64 _userId = 0;
                Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
                bool _newuser = false;
                if (Session[General.UserId] != null)
                {
                    _userId = Convert.ToInt64(Session[General.UserId].ToString());
                }
                else
                {
                    _newuser = true;
                }

                if (UpdateProfile(_userId, _carId) > 0)
                {
                    if (_newuser)
                    {
                        SendMailToUser(txtEmailAddress.Text.Trim(), Session[CE.Global.General.UserName].ToString(), txtMobileNo.GetPhoneNo());
                    }
                    int resultCalculatePremium = CalculatePremium();
                    #region Edit Change Class

                    if (Convert.ToInt32(ddlInsuranceType.Text) == 10)
                    {
                        if (resultCalculatePremium == 0)
                        {
                            CarPolicy _carpolicy = new CarPolicy();
                            CarPolicyDB _carpolicydb = new CarPolicyDB();
                            if (Session[General.CarPolicyId] != null)
                            {
                                //CAR POLICY DETAILS
                                //Change to 2+
                                Int64 _refceuserid = 0;
                                Int64 _carid = 0;

                                if (Session[General.UserId] != null)
                                {
                                    _refceuserid = Convert.ToInt64(Session[General.UserId].ToString());
                                }

                                if (Session[General.CarId] != null)
                                {
                                    _carid = Convert.ToInt64(Session[General.CarId].ToString());
                                }

                                _carpolicy = _carpolicydb.GetCarPolicy(_carid, _refceuserid);
                                if (_carpolicy != null)
                                {
                                    //_carpolicy.Info5 = "UPDATE";
                                    _carpolicy.InsuranceType = 21;
                                    if (_carpolicy.Deductible == -1 || _carpolicy.Deductible == 5000)
                                    {
                                        _carpolicy.Deductible = 0;
                                    }
                                    _carpolicy.IsCTPL = false;
                                    _carpolicy.IsAddDriver = false;
                                    _carpolicy.NoOfDriver = 0;

                                    CarDriverDB _cardriverdb = new CarDriverDB();
                                    _cardriverdb.UpdateAllStatus(_carid, _refceuserid);
                                    _cardriverdb = null;
                                    Int64 _policyresult = 0;
                                    _policyresult = _carpolicydb.Insert(_carpolicy);

                                    resultCalculatePremium = CalculatePremium();
                                }
                            }
                            _carpolicy = null;
                            _carpolicydb = null;
                        }
                    }

                    #endregion

                    ResultsQuotesDataBind();

                    switch (Convert.ToInt32(ddlInsuranceType.Text))
                    {
                        case 10:
                            divGarageType.Style.Add("display", "");
                            divYesAccMod.Style.Add("display", "");
                            divProvinceofRegistration.Style.Add("display", "");
                            idAnyClaimLastYear.Style.Add("display", "");
                            //idNCB.Style.Add("display", "");
                            divDriver.Style.Add("display", "");
                            divDeduct.Style.Add("display", "");
                            divCTPL.Style.Add("display", "none");
                            break;
                        case 21:
                        case 31:
                            divGarageType.Style.Add("display", "");
                            divDeduct.Style.Add("display", "");
                            divProvinceofRegistration.Style.Add("display", "none");
                            idAnyClaimLastYear.Style.Add("display", "none");
                            //idNCB.Style.Add("display", "none");
                            divDriver.Style.Add("display", "none");
                            divYesAccMod.Style.Add("display", "none");
                            divCTPL.Style.Add("display", "none");
                            break;
                        case 30:
                            divCTPL.Style.Add("display", "");
                            divGarageType.Style.Add("display", "none");
                            divProvinceofRegistration.Style.Add("display", "none");
                            idAnyClaimLastYear.Style.Add("display", "none");
                            //idNCB.Style.Add("display", "none");
                            divDriver.Style.Add("display", "none");
                            divYesAccMod.Style.Add("display", "none");
                            divDeduct.Style.Add("display", "none");
                            break;
                    }
                }
            }
            else
            {
                lblMessage.Text = "Saving did NOT succeed!";
            }
        }
        else
        {
            lblMessage.Text = "Please fill all require fields completly and correctly.";
        }
    }

    private void ClickOnceButton(Page page, Button b)
    {
        System.Text.StringBuilder oneClickScript = new System.Text.StringBuilder();
        oneClickScript.Append("if (typeof(Page_ClientValidate) == 'function') { ");
        oneClickScript.Append("if (Page_ClientValidate() == false) { return false; }} ");
        oneClickScript.Append("this.value = 'Processing...';");
        oneClickScript.Append("this.disabled = true;");
        oneClickScript.Append(page.ClientScript.GetPostBackEventReference(b, ""));
        oneClickScript.Append(";");
        b.Attributes.Add("onclick", oneClickScript.ToString());
    }

    private Int64 LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        return _userviewdb.LogViewedHistory("CI", Request, "Car Insurance car detail.");
    }

    private bool Save()
    {
        Int64 _carresult = 0;
        Int64 _policyresult = 0;

        CarDetailTH _car = new CarDetailTH();
        CarDetailTHDB _cardb = new CarDetailTHDB();

        ProfileDB _profiledb = new ProfileDB();
        Profile _profile = new Profile();

        Contact _contact = new Contact();
        ContactDB _contactdb = new ContactDB();

        Int64 _refceuserid = 0;

        if (Session[General.CarId] != null)
        {
            _car = _cardb.GetCar(Convert.ToInt64(Session[General.CarId].ToString()), 0);
            if (Session[General.AgentId] != null)
            {
                _car.Info5 = "UPDATE";
            }
        }
        else
        {
            if (Session[General.AgentId] != null)
            {
                _car.Info4 = "NEW";
            }
        }

        if (Session[General.ViewedDetailsId] == null)
        {
            Session[General.ViewedDetailsId] = LogUserViewedHistory().ToString();
        }

        if (_car == null)
        {
            _car = new CarDetailTH();
        }

        if (Session[CE.Global.General.UserId] != null)
        {
            _refceuserid = Convert.ToInt64(Session[CE.Global.General.UserId]);
            _profile = _profiledb.GetProfile(_refceuserid);
            _contact = _contactdb.GetContact(_refceuserid);
            if (_profile != null && _contact != null)
            {
                _car.Info5 = _contact.Email;
                _car.Info6 = _contact.Mobile;
                _car.Info7 = _profile.SurName;
                if (_profile.FirstName.Trim().Length > 0)
                {
                    _car.Info8 = _profile.FirstName;
                }
                _car.Info9 = (_profile.Gender.ToString().Trim() != "" ? _profile.Gender.ToString() : "M"); //ddlGender.GetGender();
                if (_profile.DOB.Year == 1900)
                {
                    DateTime dteDOB = new DateTime(1995, 1, 1);
                    _car.Info10 = dteDOB.ToString("dd-MMM-yyyy");
                }
                else
                {
                    _car.Info10 = _profile.DOB.ToString("dd-MMM-yyyy"); 
                }
                _car.Info11 = _profile.Occupation.ToString();
                _car.Info12 = _profile.JobNature;
                _car.Info13 = _profile.MaritalStatus.ToString();
                _car.Info14 = "0";
                _car.Info15 = _profile.Salutation;
                _profile = null;
                _contact = null;
            }
        }

        _car.ManufactYear = Convert.ToInt32(ddlManufactYear.Text);
        if (Session[General.AgentId] != null)
        {
            _car.Info2 = Session[General.AgentId].ToString();
            _car.Info3 = General.GetUTCDateTime().ToString();
        }

        _car.CarMakeName = ddlCarMake.Text;
        string[] _tempDesc = ddlModelBodyCCDoor.SelectedValue.Split(' ');
        if (_tempDesc.Length == 5)
        {
            _car.CarModelName = _tempDesc[0];
            _car.Body = _tempDesc[1];
            _car.CC = Convert.ToInt32(_tempDesc[2].Substring(0, _tempDesc[2].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[3]);
        }
        else if (_tempDesc.Length == 6)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1];
            _car.Body = _tempDesc[2];
            _car.CC = Convert.ToInt32(_tempDesc[3].Substring(0, _tempDesc[3].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[4]);
        }
        else if (_tempDesc.Length == 7)
        {
            _car.CarModelName = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
            _car.Body = _tempDesc[3];
            _car.CC = Convert.ToInt32(_tempDesc[4].Substring(0, _tempDesc[4].Length - 2));
            _car.Door = Convert.ToInt32(_tempDesc[5]);
        }
        _car.GroupNo = Convert.ToInt32(txtGroupNo.Text);
        _car.Info2 = lblCarVehicleType.Text;
        //LC = 210 or 220
        //PS = 110 or 120
        //PU = 320
        //SV = 110 or 120
        if (lblCarVehicleType.Text == "PS" || lblCarVehicleType.Text == "SV" || lblCarVehicleType.Text == "")
        {
            _car.Info3 = ddlVehicleType.Text;
        }
        else if (lblCarVehicleType.Text == "LC")
        {
            if (ddlVehicleType.Text == "110")
            {
                _car.Info3 = "210";
            }
            else if (ddlVehicleType.Text == "120")
            {
                _car.Info3 = "220";
            }
        }
        else if (lblCarVehicleType.Text == "PU")
        {
            if (ddlVehicleType.Text == "110" && _car.Door == 2)
            {
                _car.Info3 = "320";
            }
            if (ddlVehicleType.Text == "110" && _car.Door == 4)
            {
                _car.Info3 = "110";
            }
            else if (ddlVehicleType.Text == "120")
            {
                _car.Info3 = "340"; //Disabled, No Packages
            }
        }
        _car.MakeModelDesc = ddlCarMake.SelectedItem.Text + " " + ddlModelBodyCCDoor.SelectedItem.Text;
        _car.Status = true;
        _car.RefCEUserId = _refceuserid;
        _car.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
        _car.CurrentStep = 1;
        _car.TotalStep = 4;

        if (hidCurInsuranceCompany.Value.Trim() == "") hidCurInsuranceCompany.Value = "150";
        _car.Info1 = hidCurInsuranceCompany.Value;

        _carresult = _cardb.Insert(_car);

        //**********************************************************

        _car = null;
        _cardb = null;

        if (_carresult > 0)
        {
            Session[CE.Global.General.CarId] = _carresult.ToString();
        }
        else
        {
            lblMessage.Text = "Insert error!";
        }
        //return _result > 0;
        if (_carresult > 0)
        {
            //CAR POLICY DETAILS
            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            Int64 _carId = Convert.ToInt64(Session[General.CarId].ToString());
            Int64 _carpolicyid = 0;

            if (Session[General.CarPolicyId] != null)
            {
                _carpolicyid = Convert.ToInt64(Session[General.CarPolicyId].ToString());
                _carpolicy.CECarPolicyId = _carpolicyid;
                if (Session[General.AgentId] != null)
                {
                    _carpolicy.Info5 = "UPDATE";
                }
            }
            else
            {
                if (Session[General.AgentId] != null)
                {
                    _carpolicy.Info4 = "NEW";
                }
            }

            lblMessage.Text = "";
            if (Session[General.AgentId] != null)
            {
                _carpolicy.Info2 = Session[General.AgentId].ToString();
                _carpolicy.Info3 = General.GetUTCDateTime().ToString();
            }

            _carpolicy.CECarId = _carId;
            _carpolicy.InsuranceType = Convert.ToInt32(ddlInsuranceType.Text);
            _carpolicy.GarageType = Convert.ToInt32(ddlGarageType.Text);
            _carpolicy.VehicleType = Convert.ToInt32(ddlVehicleType.Text);
            _carpolicy.SumInsured = Convert.ToInt32(txtSumInsured.Text);
            _carpolicy.ProvinceRegistration = ddlProvinceRegistration.Text;
            _carpolicy.UseOfVehicle = "N/A";
            string strDate = hidCoverageCommenceDate.Value;
            int _iDay = Convert.ToInt32(strDate.Substring(0, 2));
            int _iMonth = Convert.ToInt32(strDate.Substring(2, 2));
            int _iYear = Convert.ToInt32(strDate.Substring(4, 4));
            if (_iYear > 1)
            {
                _carpolicy.CoverageCommenceDate = new DateTime(_iYear, _iMonth, _iDay); 
            }
            else
            {
                _carpolicy.CoverageCommenceDate = General.GetUTCDateTimeToday().AddDays(14);
            }
            _carpolicy.IsRedPlate = false;

            if (ddlInsuranceType.SelectedValue == "10" || ddlInsuranceType.SelectedValue == "11")
            {
                _carpolicy.IsAddAccMod = rdoYesAccMod.Checked;
                if (rdoYesAccMod.Checked)
                {
                    int _tmpAccModAmount = 0;
                    if (Int32.TryParse(txtAccModAmount.Text, out _tmpAccModAmount))
                    {
                        _carpolicy.AddAccModAmount = _tmpAccModAmount;
                    }
                }
                else
                {
                    _carpolicy.AddAccModAmount = 0;
                }
                if (Convert.ToInt32(ddlNCB.Text) >= 0)
                {
                    _carpolicy.NCDPercent = Convert.ToInt32(ddlNCB.Text);
                }
                else
                {
                    _carpolicy.NCDPercent = 0;
                }
                _carpolicy.IsClaimLastYear = rdoYesClaimLastYear.Checked;
                _carpolicy.IsCTPL = rdoYesCTPL.Checked;
                _carpolicy.IsAddDriver = rdoYesAddDriver.Checked;
                if (rdoYesAddDriver.Checked)
                {
                    _carpolicy.NoOfDriver = Convert.ToInt16(ddlDriverCount.SelectedValue);
                }
                else
                {
                    _carpolicy.NoOfDriver = 0;
                }
            }
            else
            {
                _carpolicy.IsAddAccMod = false;
                _carpolicy.AddAccModAmount = 0;
                _carpolicy.NCDPercent = 0;
                _carpolicy.IsClaimLastYear = false;
                if (ddlInsuranceType.SelectedValue == "30")
                {
                    _carpolicy.IsCTPL = rdoYesCTPL.Checked;
                }
                _carpolicy.IsAddDriver = false;
                _carpolicy.NoOfDriver = 0;
            }

            if (ddlInsuranceType.SelectedValue == "21" || ddlInsuranceType.SelectedValue == "31")
            {
                if (Convert.ToInt16(ddlDeduct.SelectedValue) == 5000)
                {
                    _carpolicy.Deductible = 2000;
                }
                else
                {
                    _carpolicy.Deductible = Convert.ToInt16(ddlDeduct.SelectedValue);
                }
            }
            else
            {
                _carpolicy.Deductible = Convert.ToInt16(ddlDeduct.SelectedValue);
            }

            if (hidCurrentInsurer.Value.Trim() == "") hidCurrentInsurer.Value = Resources.CarInsurance.Others;
            _carpolicy.CurrentInsurer = hidCurrentInsurer.Value; 
            _carpolicy.RefCEUserId = _refceuserid;
            _carpolicy.Status = true;
            _carpolicy.CurrentStep = 2;
            _policyresult = _carpolicydb.Insert(_carpolicy);
            if (_policyresult > 0)
            {
                Session[General.CarPolicyId] = _policyresult.ToString();

                lblMessage.Text += "<br>Car policy saved successfully!";
                lblMessage.ForeColor = System.Drawing.Color.Blue;
            }
            else
            {
                lblMessage.Text = "Car policy did not save successfully!";
                lblMessage.ForeColor = System.Drawing.Color.Red;
                return false;
            }

            CarDriver _cardriver = new CarDriver();
            CarDriverDB _cardriverdb = new CarDriverDB();

            if (rdoYesAddDriver.Checked == true)
            {
                int _drivercount = Convert.ToInt32(ddlDriverCount.SelectedValue);
                int _insertcount = 0;
                _cardriverdb.UpdateAllStatus(_carId, _refceuserid);

                for (int i = 1; i <= _drivercount; i++)
                {
                    _cardriver.StepId = 1;
                    _cardriver.RerCEUserId = _refceuserid;
                    _cardriver.CECarId = _carId;
                    if (i == 1)
                    {
                        UsrCarDriver1.SetProperty();
                        UsrCarDriver1.IsEnabled = true;
                        _cardriver.CarDriverId = UsrCarDriver1.DriverId;
                        _cardriver.DOB = UsrCarDriver1.DOB;
                        _cardriver.Status = "Active";
                    }
                    else if (i == 2)
                    {
                        UsrCarDriver2.SetProperty();
                        UsrCarDriver2.IsEnabled = true;
                        _cardriver.CarDriverId = UsrCarDriver2.DriverId;
                        _cardriver.DOB = UsrCarDriver2.DOB;
                        _cardriver.Status = "Active";
                    }
                
                    _cardriver.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());
                    if (_cardriverdb.Insert(_cardriver) > 0)
                    {
                        _insertcount++;
                    }
                }

                _cardriverdb = null;
                _cardriver = null;

                if (_insertcount == _drivercount)
                {
                    lblMessage.Text += "<br>All drivers are successfully saved!";
                    lblMessage.ForeColor = System.Drawing.Color.Blue;
                }
                else
                {
                    lblMessage.Text += "<br>All drivers are did not saved!";
                    lblMessage.ForeColor = System.Drawing.Color.Red;
                    return false;
                }
            }
            else
            {
                _cardriverdb.UpdateAllStatus(_carId, _refceuserid);
            }

            _carpolicy = null;
            _carpolicydb = null;
        }

        return _policyresult > 0;
    }

    private void GenerateServerSideCarModel(int CarMakeId)
    {
        CarDetailDB _cardeaildb = new CarDetailDB();
        Int64 _carmakecount = _cardeaildb.GetCarModelCount(CarMakeId);
        DataTable _dtCarModel = _cardeaildb.GetCarModel(CarMakeId);
        if (_dtCarModel != null)
        {
            if (_dtCarModel.Rows.Count > 0)
            {
                int _rowCount = _dtCarModel.Rows.Count;
                for (int i = 0; i < _rowCount; i++)
                {
                }
            }
        }
    }

    private void ChangeValidationEffectServerSide(string strValidationGroup)
    {
        //Insurance Type
        if (rfvInsuranceType.Enabled && rfvInsuranceType.ValidationGroup == strValidationGroup)
        {
            rfvInsuranceType.Validate();
            if (rfvInsuranceType.IsValid == false)
            {
                ddlInsuranceType.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlInsuranceType.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlInsuranceType.ControlStyle.CssClass = "";
        }

        //Garage Type
        if (rfvGarageType.Enabled && rfvGarageType.ValidationGroup == strValidationGroup)
        {
            rfvGarageType.Validate();
            if (rfvGarageType.IsValid == false)
            {
                ddlGarageType.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlGarageType.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlGarageType.ControlStyle.CssClass = "";
        }

        //Vehicle Type
        if (rfvVehicleType.Enabled && rfvVehicleType.ValidationGroup == strValidationGroup)
        {
            rfvVehicleType.Validate();
            if (rfvVehicleType.IsValid == false)
            {
                ddlVehicleType.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlVehicleType.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlVehicleType.ControlStyle.CssClass = "";
        }

        //Year of Manufaturer
        if (rfvManufactYear.Enabled && rfvManufactYear.ValidationGroup == strValidationGroup)
        {
            rfvManufactYear.Validate();
            if (rfvManufactYear.IsValid == false)
            {
                ddlManufactYear.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlManufactYear.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlManufactYear.ControlStyle.CssClass = "";
        }

        if (rfvCarMake.Enabled && rfvCarMake.ValidationGroup == strValidationGroup)
        {
            rfvCarMake.Validate();
            if (rfvCarMake.IsValid == false)
            {
                ddlCarMake.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlCarMake.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlCarMake.ControlStyle.CssClass = "";
        }

        if (rfvModelBodyCCDoor.Enabled && rfvModelBodyCCDoor.ValidationGroup == strValidationGroup)
        {
            rfvModelBodyCCDoor.Validate();
            if (rfvModelBodyCCDoor.IsValid == false)
            {
                ddlModelBodyCCDoor.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlModelBodyCCDoor.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlModelBodyCCDoor.ControlStyle.CssClass = "";
        }

        if (rfvSumInsured.Enabled && rfvSumInsured.ValidationGroup == strValidationGroup)
        {
            rfvSumInsured.Validate();
            if (rfvSumInsured.IsValid == false)
            {
                txtSumInsured.ControlStyle.CssClass = "validationError";
            }
            else
            {
                txtSumInsured.ControlStyle.CssClass = "";
            }
        }
        else
        {
            txtSumInsured.ControlStyle.CssClass = "";
        }

        //rfvProvinceRegistration
        if (rfvProvinceRegistration.Enabled && rfvProvinceRegistration.ValidationGroup == strValidationGroup)
        {
            rfvProvinceRegistration.Validate();
            if (rfvProvinceRegistration.IsValid == false)
            {
                ddlProvinceRegistration.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlProvinceRegistration.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlProvinceRegistration.ControlStyle.CssClass = "";
        }

        //NCB
        if (rfvNCB.Enabled && rfvNCB.ValidationGroup == strValidationGroup)
        {
            rfvNCB.Validate();
            if (rfvNCB.IsValid == false)
            {
                ddlNCB.ControlStyle.CssClass = "validationError";
            }
            else
            {
                ddlNCB.ControlStyle.CssClass = "";
            }
        }
        else
        {
            ddlNCB.ControlStyle.CssClass = "";
        }

        //Any Claims in the Last 3 Years?
        if (rfvAnyClaim.Enabled && rfvAnyClaim.ValidationGroup == strValidationGroup)
        {
            rfvAnyClaim.Validate();
            if (rfvAnyClaim.IsValid == false)
            {
                lblYesClaimLastYear.ControlStyle.CssClass = "validationError";
                lblNoClaimLastYear.ControlStyle.CssClass = "validationError";
            }
            else
            {
                lblYesClaimLastYear.ControlStyle.CssClass = "";
                lblNoClaimLastYear.ControlStyle.CssClass = "";
            }
        }
        else
        {
            lblYesClaimLastYear.ControlStyle.CssClass = "";
            lblNoClaimLastYear.ControlStyle.CssClass = "";
        }

        //CTPL
        if (rfvCTPL.Enabled && rfvCTPL.ValidationGroup == strValidationGroup)
        {
            rfvCTPL.Validate();
            if (rfvCTPL.IsValid == false)
            {
                lblYesCTPL.ControlStyle.CssClass = "validationError";
                lblNoCTPL.ControlStyle.CssClass = "validationError";
            }
            else
            {
                lblYesCTPL.ControlStyle.CssClass = "";
                lblNoCTPL.ControlStyle.CssClass = "";
            }
        }
        else
        {
            lblYesCTPL.ControlStyle.CssClass = "";
            lblNoCTPL.ControlStyle.CssClass = "";
        }

        //Add Additional Name Driver
        if (rfvAddDriver.Enabled && rfvAddDriver.ValidationGroup == strValidationGroup)
        {
            rfvAddDriver.Validate();
            if (rfvAddDriver.IsValid == false)
            {
                lblYesAddDriver.ControlStyle.CssClass = "validationError";
                lblNoAddDriver.ControlStyle.CssClass = "validationError";
            }
            else
            {
                lblYesAddDriver.ControlStyle.CssClass = "";
                lblNoAddDriver.ControlStyle.CssClass = "";
            }
        }
        else
        {
            lblYesAddDriver.ControlStyle.CssClass = "";
            lblNoAddDriver.ControlStyle.CssClass = "";
        }

        //Car Driver
        UsrCarDriver1.ChangeValidationEffectServerSide("cardetail");
        UsrCarDriver2.ChangeValidationEffectServerSide("cardetail");
    }

    private void ShowCarAndPolicyDetail(Int64 CarId, Int64 PolicyId, Int64 UserId)
    {
        CarDetailTH _cardetail = new CarDetailTH();
        CarDetailTHDB _cardetaildb = new CarDetailTHDB();
        _cardetail = _cardetaildb.GetCar(CarId, UserId);

        CarPolicy _carpolicy = new CarPolicy();
        CarPolicyDB _carpolicydb = new CarPolicyDB();
        _carpolicy = _carpolicydb.GetCarPolicy(CarId, PolicyId, UserId);

        if (_carpolicy != null && _cardetail != null)
        {
            SetProperty(_carpolicy, _cardetail);
        }

        _cardetail = null;
        _cardetaildb = null;

        _carpolicy = null;
        _carpolicydb = null;
    }

    private void SetProperty(CarPolicy _CarPolicy, CarDetailTH _CarDetail)
    {
        ddlInsuranceType.Text = _CarPolicy.InsuranceType.ToString();
        ddlGarageType.Text = _CarPolicy.GarageType.ToString();
        LoadManufactYearList();

        ddlManufactYear.SelectedIndex = ddlManufactYear.Items.IndexOf(ddlManufactYear.Items.FindByValue(_CarDetail.ManufactYear.ToString()));
        ddlManufactYear_SelectedIndexChanged(null, null);
        ddlCarMake.Text = _CarDetail.CarMakeName;
        ddlCarMake_SelectedIndexChanged(null, null);
        string _tempDesc = _CarDetail.CarModelName + " " + _CarDetail.Body + " " + _CarDetail.CC + "cc " + _CarDetail.Door.ToString() + " doors";

        ddlModelBodyCCDoor.SelectedValue = _tempDesc;
        ddlModelBodyCCDoor_SelectedIndexChanged(null, null);
        hidCurInsuranceCompany.Value = _CarDetail.Info1;
        hidCurrentInsurer.Value = _CarPolicy.CurrentInsurer;
        txtGroupNo.Text = _CarDetail.GroupNo.ToString();
        lblCarVehicleType.Text = _CarDetail.Info2;
        //ChangeVehicleUsageList(lblCarVehicleType.Text);
        if (_CarDetail.Info3 == "110" || _CarDetail.Info3 == "210" || _CarDetail.Info3 == "320")
        {
            ddlVehicleType.Text = "110";
        }
        else
        {
            ddlVehicleType.Text = "120";
        }
        ddlVehicleType_SelectedIndexChanged(null, null);
        txtSumInsured.Text = _CarPolicy.SumInsured.ToString();
        lblSumInsured.Text = Convert.ToInt32(txtSumInsured.Text).ToString("#,000");

        rdoYesAccMod.Checked = _CarPolicy.IsAddAccMod;
        rdoNoAccMod.Checked = !_CarPolicy.IsAddAccMod;

        if (rdoYesAccMod.Checked)
        {
            txtNewSumInsured.Text = (_CarPolicy.SumInsured + _CarPolicy.AddAccModAmount).ToString();
            txtAccModAmount.Text = _CarPolicy.AddAccModAmount.ToString();
            lblSumInsured.Text = Convert.ToInt32(txtNewSumInsured.Text).ToString("#,000");
        }

        string _deductible = "";
        _deductible = _CarPolicy.Deductible.ToString();
        if (ddlInsuranceType.SelectedValue == "10" || ddlInsuranceType.SelectedValue == "11" ||
            ddlInsuranceType.SelectedValue == "21" || ddlInsuranceType.SelectedValue == "31")
        {
            _deductible = _CarPolicy.Deductible.ToString();
            if (_CarPolicy.Deductible == 2000)
            {
                _deductible = "5000";
            }
        }
        else
        {
            _deductible = "0";
        }
        ddlDeduct.SelectedIndex = ddlDeduct.Items.IndexOf(ddlDeduct.Items.FindByValue(_deductible)); //Convert.ToInt32(_CarPolicy.Deductible) == 0 ? "0" : "-1";

        ddlProvinceRegistration.Text = _CarPolicy.ProvinceRegistration;
        hidCoverageCommenceDate.Value = _CarPolicy.CoverageCommenceDate.Day.ToString("00") + _CarPolicy.CoverageCommenceDate.Month.ToString("00") + _CarPolicy.CoverageCommenceDate.Year.ToString("0000");
        rdoYesClaimLastYear.Checked = _CarPolicy.IsClaimLastYear;
        rdoNoClaimLastYear.Checked = !_CarPolicy.IsClaimLastYear;
        if (rdoYesClaimLastYear.Checked)
        {
            int NCB = _CarPolicy.NCDPercent;
            if (ddlNCB.Items.Count > 3 && NCB <= 20)
            {
                hidNCBClaim.Value = "1";
            }
        }

        rdoYesAddDriver.Checked = _CarPolicy.IsAddDriver;
        rdoYesAddDriver_CheckedChanged(null, null);
        rdoNoAddDriver.Checked = !_CarPolicy.IsAddDriver;
        ddlDriverCount.Text = _CarPolicy.NoOfDriver.ToString();
        rdoYesCTPL.Checked = _CarPolicy.IsCTPL;
        rdoNoCTPL.Checked = !_CarPolicy.IsCTPL;
        ddlNCB.Text = _CarPolicy.NCDPercent.ToString();

        if (_CarPolicy.NoOfDriver > 0 && rdoYesAddDriver.Checked)
        {
            divAddDriver.Visible = true;
            pnlDriver.Visible = true;
            txtAddDriver.Text = "1";

            int _noOfDriver = _CarPolicy.NoOfDriver;
            CarDriverList _cardriverlist = new CarDriverList();
            CarDriverDB _cardriverdb = new CarDriverDB();
            _cardriverlist = _cardriverdb.GetCarDriverList(_CarPolicy.CECarId, _CarPolicy.RefCEUserId);
            _cardriverdb = null;

            for (int i = 1; i <= _noOfDriver; i++)
            {
                CarDriver _cardriver = _cardriverlist[i - 1];
                if (i == 1)
                {
                    UsrCarDriver1.DriverId = _cardriver.CarDriverId;
                    UsrCarDriver1.DOB = _cardriver.DOB;
                    UsrCarDriver1.IsEnabled = true;
                }
                else if (i == 2)
                {
                    UsrCarDriver2.DriverId = _cardriver.CarDriverId;
                    UsrCarDriver2.DOB = _cardriver.DOB;
                    UsrCarDriver2.IsEnabled = true;
                }
            }
            _cardriverlist = null;
        }
        else
        {
            pnlDriver.Visible = false;
            divAddDriver.Visible = false;
            txtAddDriver.Text = "1";
        }
    }

    private void DriverSetting()
    {
        if (rdoYesAddDriver.Checked)
        {
            int _drivercount = Convert.ToInt32(ddlDriverCount.SelectedValue);
            for (int i = 1; i <= 2; i++)
            {
                string strDivName = "divDriver" + i.ToString();
                HtmlGenericControl _divDriver = (HtmlGenericControl)pnlDriver.FindControl(strDivName);
                if (i > _drivercount)
                {
                    if (_divDriver != null)
                    {
                        _divDriver.Visible = false;
                    }
                }
                else
                {
                    if (_divDriver != null)
                    {
                        _divDriver.Visible = true;
                    }
                }
            }
        }
        else
        {
            for (int i = 2; i <= 2; i++)
            {
                string strDivName = "divDriver" + i.ToString();
                HtmlGenericControl _divDriver = (HtmlGenericControl)pnlDriver.FindControl(strDivName);
                string strUsrDriver = "UsrCarDriver" + i.ToString();
                controls_usrCarDriverDetails _ctrlDriver = (controls_usrCarDriverDetails)pnlDriver.FindControl(strUsrDriver);
                if (_divDriver != null && _ctrlDriver != null)
                {
                    _divDriver.Visible = false;
                    _ctrlDriver.ClearProperty();
                    _ctrlDriver.IsEnableValidation(false);
                }

            }
        }
    }

    private void OtherValidation()
    {
        if (rdoYesClaimLastYear.Checked == false && rdoNoClaimLastYear.Checked == false)
        {
            rfvAnyClaim.IsValid = false;
        }
        else
        {
            txtAnyClaim.Text = "1";
            rfvAnyClaim.Validate();
        }

        if (rdoYesAccMod.Checked == false && rdoNoAccMod.Checked == false)
        {
            rfvAccMod.IsValid = false;
        }
        else
        {
            if (rdoYesAccMod.Checked)
            {
                rfvAccModAmount.Validate();
                revAccModAmount.Validate();
                csvAccModAmount.Validate();
            }
            else
            {
                rfvAccModAmount.Enabled = false;
                revAccModAmount.Enabled = false;
                csvAccModAmount.Enabled = false;
                txtAccModAmount.Text = "0";
            }
            txtAccMod.Text = "1";
            rfvAccMod.Validate();
        }
    }

    private int GetExistingNCD()
    {
        int ExistingNCD = 0;

        if (ddlNCB.Text == "0")
            ExistingNCD = -1;
        else
            ExistingNCD = Convert.ToInt32(ddlNCB.Text) - 10;
        return ExistingNCD;
    }

    protected void rdoYesAddDriver_CheckedChanged(object sender, EventArgs e)
    {
        if (rdoYesAddDriver.Checked)
        {
            rdoNoAddDriver.Checked = false;
            txtAddDriver.Text = "1";
            pnlDriver.Visible = true;
            divAddDriver.Visible = true;

            if (!Page.IsPostBack)
                DriverSetting();
        }
    }

    protected void rdoNoAddDriver_CheckedChanged(object sender, EventArgs e)
    {
        if (rdoNoAddDriver.Checked)
        {
            rdoYesAddDriver.Checked = false;
            txtAddDriver.Text = "1";
            pnlDriver.Visible = false;
            divAddDriver.Visible = false;

            if (!Page.IsPostBack)
                DriverSetting();

        }

    }

    protected void rdoNoCliam_CheckChange(object sender, EventArgs e)
    {
        txtAnyClaim.Text = "1";
        ddlNCB.Items.Clear();
        ddlNCB.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlNCB.Items.Add(new ListItem("0 %", "0"));
        //ddlNCB.Items.Add(new ListItem("10", "10"));
        ddlNCB.Items.Add(new ListItem("20 %", "20"));
        ddlNCB.Items.Add(new ListItem("30 %", "30"));
        ddlNCB.Items.Add(new ListItem("40 %", "40"));
        ddlNCB.Items.Add(new ListItem("50 %", "50"));
    }

    protected void CheckClaim(object sender, EventArgs e)
    {
        ddlNCB.Items.Clear();
        ddlNCB.Items.Add(new ListItem("No NCD", "0"));
    }

    protected void ddlDriverCount_SelectedIndexChanged(object sender, EventArgs e)
    {
        DriverSetting();
    }

    protected void ddlCarMake_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlCarMake.Text == "-1")
        {
            ddlModelBodyCCDoor.Items.Clear();
            ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));

            txtSumInsured.Text = "0";
            lblSumInsured.Text = "0";
            txtGroupNo.Text = "-1";
        }
        else
        {
            GetCarModelDescList(ddlCarMake.Text, ddlManufactYear.Text, ddlModelBodyCCDoor);
            if (ddlModelBodyCCDoor.Items.Count > 0)
            {
                ddlModelBodyCCDoor.SelectedIndex = 0;
                ddlModelBodyCCDoor_SelectedIndexChanged(sender, e);
            }
        }
    }

    private void ClearAllList()
    {
        ddlCarMake.Items.Clear();
        ddlCarMake.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        txtSumInsured.Text = "0";
        lblSumInsured.Text = "0";
        txtGroupNo.Text = "-1";
    }

    protected void ddlManufactYear_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            string carMakeValue = ddlCarMake.Text;
            string carModelValue = ddlModelBodyCCDoor.Text;

            if (ddlManufactYear.Text == "-1")
            {
                ClearAllList();
            }
            else
            {
                GetCarMakeList(ddlManufactYear.Text, ddlCarMake);
                if (ddlCarMake.Items.Count > 0)
                {
                    if (carMakeValue != "-1")
                    {
                        ddlCarMake.Text = carMakeValue;
                        ddlCarMake_SelectedIndexChanged(sender, e);

                        if (carModelValue != "-1" && ddlModelBodyCCDoor.Items.Count > 0)
                        {
                            ddlModelBodyCCDoor.Text = carModelValue;
                            ddlModelBodyCCDoor_SelectedIndexChanged(sender, e);
                        }
                    }
                    else
                    {

                    }
                }
            }
        }
        catch
        {

        }
    }

    protected void ddlModelBodyCCDoor_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlManufactYear.SelectedIndex >= 0 && ddlCarMake.SelectedIndex >= 0 & ddlModelBodyCCDoor.SelectedIndex >= 0)
        {
            string[] _tempDesc = ddlModelBodyCCDoor.Text.Split(' ');
            string _model = "";
            string _body = "";
            string _cc = "";
            string _door = "";
            if (_tempDesc.Length == 5)
            {
                _model = _tempDesc[0];
                _body = _tempDesc[1];
                _cc = _tempDesc[2].Substring(0, _tempDesc[2].Length - 2);
                _door = _tempDesc[3];
            }
            else if (_tempDesc.Length == 6)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1];
                _body = _tempDesc[2];
                _cc = _tempDesc[3].Substring(0, _tempDesc[3].Length - 2);
                _door = _tempDesc[4];
            }
            else if (_tempDesc.Length == 7)
            {
                _model = _tempDesc[0] + " " + _tempDesc[1] + " " + _tempDesc[2];
                _body = _tempDesc[3];
                _cc = _tempDesc[4].Substring(0, _tempDesc[4].Length - 2);
                _door = _tempDesc[5];
            }
            lblModelDesc.Text = "model : " + _model + ", body: " + _body + ", cc: " + _cc + ", door: " + _door;
            GetCarModelSumInsuredAmountAndVehicleType(ddlCarMake.Text, _model, _body, _cc, _door, ddlManufactYear.Text, txtSumInsured, lblSumInsured, lblCarVehicleType);
            txtNewSumInsured.Text = txtSumInsured.Text;
            if (rdoYesAccMod.Checked)
            {
                if (txtAccModAmount.Text.Length > 0)
                {
                    int _sumInsured = Convert.ToInt32(txtSumInsured.Text);
                    int _tmpAmount = 0;
                    if (Int32.TryParse(txtAccModAmount.Text, out _tmpAmount))
                    {
                        _sumInsured += _tmpAmount;
                        txtNewSumInsured.Text = _sumInsured.ToString();
                        lblSumInsured.Text = Convert.ToInt32(txtNewSumInsured.Text).ToString("#,000");
                    }
                    else
                    {
                        txtNewSumInsured.Text = _sumInsured.ToString();
                        txtAccModAmount.Text = "";
                    }
                }
            }
            GetCarModelGroupNo(ddlCarMake.Text, _model, _body, _cc, _door, txtGroupNo);
        }
    }

    private void ChangeVehicleUsageList(string CarVehicleType)
    {
        ddlVehicleType.Items.Clear();
        ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        if (CarVehicleType == "PU")
        {
            ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.VehicleType_Private, "110"));
        }
        else
        {
            ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.VehicleType_Private, "110"));
            ddlVehicleType.Items.Add(new ListItem(Resources.CarInsurance.VehicleType_Commercial, "120"));
        }
        rdoNoAddDriver.Checked = false;
        rdoYesAddDriver.Checked = false;
        divSpecifyDriver.Visible = false;
        divAddDriver.Visible = false;
    }

    private void GetCarMakeList(string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblMake");
        SortedList _spList = new SortedList();
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarMakeTHListByYear", _spList);
        ddlList.Items.Clear();
        ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            for (int i = 0; i < _dt.Rows.Count; i++)
            {
                ddlList.Items.Add(new ListItem(_dt.Rows[i][1].ToString(), _dt.Rows[i][0].ToString()));
            }
        }

        _dt = null;
        _db = null;
    }

    private void GetCarModelDescList(string CarMake, string Year, DropDownList ddlList)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelDesc");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelDescTHListByCarMakeCode", _spList);
        ddlList.Items.Clear();
        ddlModelBodyCCDoor.Items.Clear();
        ddlModelBodyCCDoor.Items.Add(new ListItem(Resources.CarInsurance.Select, "-1"));
        if (_dt != null && _dt.Rows.Count > 0)
        {
            ddlModelBodyCCDoor.DataSource = _dt;
            ddlModelBodyCCDoor.DataValueField = "CarModelDesc";
            ddlModelBodyCCDoor.DataTextField = "CarModelDisplay";
            ddlModelBodyCCDoor.DataBind();
            ddlModelBodyCCDoor.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        else
        {
            ddlList.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
        }
        _dt = null;
        _db = null;
    }

    private void GetCarModelSumInsuredAmountAndVehicleType(string CarMake, string CarModel, string Body, string CC, string Door, string Year, TextBox txtTextBox, Label lblLabel, Label lblLabelTwo)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _spList.Add("@Year", Year);
        _dt = _db.GetDataTableBySP("sprocGetCarModelSumInsuredAndVehicleTypeTHListByYear", _spList);
        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
            lblLabelTwo.Text = _dt.Rows[0][1].ToString();
            lblLabel.Text = Convert.ToInt32(txtTextBox.Text).ToString("#,000");
        }
        else
        {
            txtTextBox.Text = "0";
            lblLabel.Text = "0";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    private void GetCarModelGroupNo(string CarMake, string CarModel, string Body, string CC, string Door, TextBox txtTextBox)
    {
        MyDatabase _db = new MyDatabase();
        DataTable _dt = new DataTable("tblModelBody");
        SortedList _spList = new SortedList();
        _spList.Add("@CarMake", CarMake);
        _spList.Add("@CarModel", CarModel);
        _spList.Add("@Body", Body);
        _spList.Add("@CC", CC);
        _spList.Add("@Door", Door);
        _dt = _db.GetDataTableBySP("sprocGetCarModelGroupTH", _spList);

        if (_dt != null && _dt.Rows.Count > 0)
        {
            txtTextBox.Text = _dt.Rows[0][0].ToString();
        }
        else
        {
            txtGroupNo.Text = "-1";
        }
        txtTextBox.ReadOnly = true;
        _dt = null;
        _db = null;
    }

    private void LoadManufactYearList()
    {
        int _yearCount = 9;

        ddlManufactYear.Items.Clear();

        if (ddlInsuranceType.Text != "-1")
        {
            _yearCount = 19;
            int _startYear = General.GetUTCDateTime().Year - _yearCount;
            int _endYear = General.GetUTCDateTime().Year;
            for (int i = _endYear; i >= _startYear; i--)
            {
                if (System.Globalization.CultureInfo.CurrentCulture.Name != "th-TH")
                {
                    ddlManufactYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
                else
                {
                    ddlManufactYear.Items.Add(new ListItem(i.ToString() + " - พ.ศ. " + (i + 543).ToString(), i.ToString()));
                }
            }
        }
        ddlManufactYear.Items.Insert(0, new ListItem(Resources.CarInsurance.Select, "-1"));
    }

    protected void ddlVehicleType_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (ddlVehicleType.Text == "110")
        {
            if (lblCarVehicleType.Text == "PU")
            {
                //if (ddlVehicleType.Text == "110")
                //{
                //    _car.Info3 = "320";
                //}
                //else if (ddlVehicleType.Text == "120")
                //{
                //    _car.Info3 = "340"; //Disabled, No Packages
                //}

                //divSpecifyDriver.Visible = false;
            }
            else
            {
                divSpecifyDriver.Visible = true;
            }
        }
        else
        {
            divSpecifyDriver.Visible = false;
            rdoNoAddDriver.Checked = true;
            rdoNoAddDriver_CheckedChanged(sender, e);
        }

    }

    protected void CheckAccModAmount(object sender, ServerValidateEventArgs e)
    {
        e.IsValid = true;
    }

    protected void ddlInsuranceType_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (Convert.ToInt32(ddlInsuranceType.Text) == 10)
            {
                ddlNCB.SelectedIndex = ddlNCB.Items.IndexOf(ddlNCB.Items.FindByValue("20"));
            }
            else if (Convert.ToInt32(ddlInsuranceType.Text) == 30)
            {
                ddlDeduct.SelectedIndex = 0;
            }
        }
        catch
        {

        }
    }

    #region YourDetail

    CE.User.Profile _profile = null;
    CE.User.ProfileDB _profiledb = null;
    Contact _contact = null;
    ContactDB _contactdb = null;
    private void ShowCustomerDetailByCar(Int64 CarId)
    {
        CarDetailTH _cardetail = new CarDetailTH();
        CarDetailTHDB _cardetaildb = new CarDetailTHDB();

        _cardetail = _cardetaildb.GetCar(CarId, 0);
        if (_cardetail != null)
        {
            if (_cardetail.Info5.Length > 0 &&
                _cardetail.Info6.Length > 0 &&
                _cardetail.Info7.Length > 0 &&
                _cardetail.Info8.Length > 0 &&
                _cardetail.Info9.Length > 0 &&
                _cardetail.Info10.Length > 0 &&
                _cardetail.Info11.Length > 0 &&
                _cardetail.Info12.Length > 0 &&
                _cardetail.Info13.Length > 0 &&
                _cardetail.Info14.Length > 0)
            {
                txtEmailAddress.Text = _cardetail.Info5;
                txtMobileNo.PhoneNo = _cardetail.Info6;
                if (_cardetail.Info8.Length > 0)
                {
                    txtName.Text = _cardetail.Info8 + (_cardetail.Info7.Trim() != "" ? " " + _cardetail.Info7.Trim() : "");
                }
                ddlOccupation.Occupation = _cardetail.Info11;
            }
            else
            {
                if (Session[General.UserId] != null)
                {
                    ShowCustomerDetail(Convert.ToInt64(Session[General.UserId].ToString()));
                }
            }
        }
    }

    private void ShowCustomerDetail(Int64 UserId)
    {
        _profile = new CE.User.Profile();
        _profiledb = new ProfileDB();
        _contact = new Contact();
        _contactdb = new ContactDB();

        _profile = _profiledb.GetProfile(UserId);
        _profiledb = null;

        if (_profile != null)
        {
            txtName.Text = _profile.FirstName + (_profile.SurName.Trim() != "" ? " " + _profile.SurName : "");
            ddlOccupation.Occupation = _profile.Occupation.ToString();
            _contact = _contactdb.GetContact(UserId);
            if (_contact != null)
            {
                txtMobileNo.PhoneNo = _contact.Mobile;
                txtEmailAddress.Text = _contact.Email;
                txtEmailAddress.ReadOnly = true;
            }
            _profile = null;
        }
    }

    private Int64 UpdateProfile(Int64 UserId, Int64 CarId)
    {
        Int64 _retValue = 0;
        txtName.Text = CE.Global.General.ClearScriptTag(txtName.Text.Trim());
        if (UserId != 0)
        {
            _profile = new CE.User.Profile();
            _profiledb = new ProfileDB();

            _contact = new Contact();
            _contactdb = new ContactDB();

            _profile = _profiledb.GetProfile(UserId);
            _contact = _contactdb.GetContact(UserId);

            if (_profile != null)
            {
                #region Update Profile

                _profile.Salutation = ""; 
                _profile.FirstName = Server.HtmlEncode(txtName.Text);
                _profile.SurName = "";
                _profile.Occupation = Convert.ToInt32(ddlOccupation.GetOccupation());
                _profile.Status = "Complete";

                _retValue = _profiledb.Insert(_profile);

                if (_retValue > 0 && _contact != null)
                {
                    _contact.Mobile = txtMobileNo.GetPhoneNo();
                    _contact.Status = true;

                    _retValue = _contactdb.Insert(_contact);
                }
                else
                {
                }

                if (_retValue > 0)
                {
                    if (_profile.FirstName != string.Empty)
                    {
                        Session[CE.Global.General.UserName] = _profile.FirstName + " " + _profile.SurName;
                    }
                    else
                    {
                        Session[CE.Global.General.UserName] = _profile.SurName;
                    }
                    Session[General.UserPhoneNo] = txtMobileNo.GetPhoneNo();
                    Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    if (Convert.ToInt32(Session[CE.Global.General.UserTypeId]) ==
                        Convert.ToInt32(CE.Global.CEUserType.Provider))
                    {
                        Session[CE.Global.General.ProviderProfileFirstTime] = "0";
                    }
                }
                else
                {
                }

                _profile = null;
                _contact = null;
                #endregion
            }
        }
        else
        {
            _retValue = SaveNewCustomer();
            UserId = _retValue;
        }

        if (_retValue > 0)
        {
            CarDetailTH _cardetail = new CarDetailTH();
            CarDetailTHDB _cardetaildb = new CarDetailTHDB();
            _cardetail = _cardetaildb.GetCar(CarId, UserId);

            if (_cardetail != null)
            {
                _cardetail.Info5 = txtEmailAddress.Text;
                _cardetail.Info6 = txtMobileNo.GetPhoneNo();
                _cardetail.Info7 = ""; 
                if (txtName.Text.Trim().Length > 0)
                {
                    _cardetail.Info8 = Server.HtmlEncode(txtName.Text);
                }
                _cardetail.Info9 = "";
                _cardetail.Info10 = ""; 
                _cardetail.Info11 = ddlOccupation.GetOccupation();
                _cardetail.Info12 = "";
                _cardetail.Info13 = "";
                _cardetail.Info14 = "";
                _cardetail.Info15 = "";
                _cardetail.RefCEUserId = UserId;
            }

            //RefUserId only update
            CarPolicy _carpolicy = new CarPolicy();
            CarPolicyDB _carpolicydb = new CarPolicyDB();
            _carpolicy = _carpolicydb.GetCarPolicy(CarId, UserId);
            _carpolicy.RefCEUserId = UserId;

            _retValue = _cardetaildb.Insert(_cardetail);

            _retValue = _carpolicydb.Insert(_carpolicy);

            //update RefIds
            CarDetailTHDB cardb = new CarDetailTHDB();
            cardb.UpdateCarDetailPolicy(CarId, UserId);

            if (_retValue <= 0)
            {
            }
        }

        return _retValue;
    }

    private Int64 SaveNewCustomer()
    {
        #region New Customer
        Int64 _retVal = 0;
        if (Page.IsValid)
        {

            Account _useraccount = new Account();
            AccountDB _useraccountdb = new AccountDB();

            if (_useraccountdb.IsAlreadyExist(txtEmailAddress.Text.Trim(), Convert.ToInt32(CE.Global.CEUserType.Customer)))
            {
                txtEmailAddress.ControlStyle.CssClass = "validationError";
                _retVal = 0;
            }
            else
            {
                Profile _userprofile = new Profile();
                ProfileDB _userprofiledb = new ProfileDB();
                Contact _contact = new Contact();
                ContactDB _contactdb = new ContactDB();

                long _result = -1;
                _useraccount.Email = txtEmailAddress.Text.ToLower();
                string _authcode = txtMobileNo.GetPhoneNo();                
                _useraccount.AuthCode = _authcode;
                _useraccount.UserId = "CEUSERAUTOIDCI";
                _useraccount.UserTypeId = Convert.ToInt32(CE.Global.CEUserType.Customer);
                _useraccount.IsAcceptTC = false;
                _useraccount.Status = true;
                _useraccount.RefCEUserID = -1;

                _result = _useraccountdb.Insert(_useraccount);
                _useraccount.CEID = _result;
                _retVal = _useraccount.CEID;

                if (_result > 0)
                {
                    _userprofile.Salutation = ""; 
                    _userprofile.FirstName = Server.HtmlEncode(txtName.Text);
                    _userprofile.SurName = "";
                    _userprofile.Gender = (char)' ';
                    _userprofile.Occupation = Convert.ToInt32(ddlOccupation.GetOccupation());
                    _userprofile.Status = "Complete";
                    _userprofile.RefCEUserId = _useraccount.CEID;
                    _userprofile.IsAcceptTC = checkIsAgreement.Checked;
                    _result = _userprofiledb.Insert(_userprofile);
                    _contact.Email = _useraccount.Email;
                    _contact.Mobile = txtMobileNo.GetPhoneNo();
                    _contact.Status = true;
                    _contact.RefCEUserId = _useraccount.CEID;
                    _result = _contactdb.Insert(_contact);

                    if (_result > 0)
                    {
                        SaveUserLoginInformation(_useraccount.CEID, _useraccount.UserTypeId);
                        Session[CE.Global.General.UserId] = _useraccount.CEID;
                        Session[CE.Global.General.UserTypeId] = _useraccount.UserTypeId;
                        Session[CE.Global.General.UserEmail] = _useraccount.Email;
                        Session[CE.Global.General.UserPhoneNo] = _contact.Mobile;
                        Session[CE.Global.General.StartTime] = General.GetUTCDateTime().ToString();
                        if (_userprofile.FirstName != string.Empty)
                        {
                            Session[CE.Global.General.UserName] = _userprofile.FirstName + " " + _userprofile.SurName;
                        }
                        else
                        {
                            Session[CE.Global.General.UserName] = _userprofile.SurName;
                        }
                        Session[CE.Global.General.UserProfileAndContactComplete] = "1";
                    }

                }

            }
        }
        else
        {
            _retVal = 0;
        }

        return _retVal;
        #endregion
    }

    private bool SendMailToUser(string EmailAddress, string UserName, string AuthCode)
    {
        bool _retVal = false;
        _retVal = CE.Email.Welcome.SendMail(EmailAddress, UserName, AuthCode);
        return _retVal;
    }

    protected bool SaveUserLoginInformation(Int64 CEID, int UserTypeId)
    {
        LoginHistory _loghis = new LoginHistory();
        LoginHistoryDB _loghisdb = new LoginHistoryDB();
        LoginInformation _loginfo = new LoginInformation();
        LoginInformationDB _loginfodb = new LoginInformationDB();

        _loghis.CEID = CEID;
        _loghis.UserTypeId = UserTypeId;
        _loghis.StartTime = General.GetUTCDateTime();
        _loghis.EndTime = General.GetUTCDateTime();
        _loghis.IsExpired = false;
        _loghis.Status = "LOGIN";

        _loghis.LoginHisId = _loghisdb.Insert(_loghis);

        if (_loghis.LoginHisId > 0)
        {
            Session[CE.Global.General.LoginHistoryId] = _loghis.LoginHisId.ToString();
            _loginfo.CEID = CEID;
            _loginfo.UserTypeId = UserTypeId;
            _loginfo.LogHisId = _loghis.LoginHisId;

            _loginfo.Browser = Request.Browser.Browser;
            _loginfo.BrowserType = Request.Browser.Type;
            _loginfo.BrowserVersion = Request.Browser.Version;
            _loginfo.MajorVersion = Request.Browser.MajorVersion.ToString();
            _loginfo.MinorVersion = Request.Browser.MinorVersionString;
            _loginfo.JavaScript = Request.Browser.JavaScript;
            _loginfo.VBScript = Request.Browser.VBScript;
            _loginfo.ActivX = Request.Browser.ActiveXControls;
            _loginfo.Frames = Request.Browser.Frames;
            _loginfo.Tables = Request.Browser.Tables;
            _loginfo.Cookies = Request.Browser.Cookies;
            _loginfo.DotNetVersion = Request.Browser.ClrVersion.ToString();
            _loginfo.JavaApplet = Request.Browser.JavaApplets;
            _loginfo.Win16 = Request.Browser.Win16;
            _loginfo.Win32 = Request.Browser.Win32;
            _loginfo.Platform = Request.Browser.Platform;
            _loginfo.UserAgent = Request.UserAgent.ToString();
            _loginfo.IpAddress = Request.UserHostAddress;
            _loginfo.HostName = Request.UserHostName;

            _loginfo.UserInfoId = _loginfodb.Insert(_loginfo);
        }

        return _loginfo.UserInfoId > 0;

    }

    #endregion

    #endregion

}
